Importjavax.swing.*;Importjava.awt.event.*;Importjava.awt.*; Public classTouchacolImplementsactionlistener{JFrame frame; Public Static voidmain (String [] args) {Touchacol game=NewTouchacol (); Game.go (); } Public voidGo () {frame=NewJFrame (); JButton Button=NewJButton ("Can You Touch me?")); Button.addactionlistener ( This); Panel Apanel=NewPanel (); Frame.setdefaultcloseoperation (Jframe.exit_on_close); Frame.getcontentpane (). Add (Borderlayout.south,button); Frame.getcontentpane (). Add (Borderlayout.center,apanel); Frame.setsize (300, 300); Frame.setvisible (true); } Public voidactionperformed (ActionEvent event) {frame.repaint (); }}
View class Touchacol
Query the Java API documentation:
ActionEvent class from Java.awt.event
Jframe,jbutton class from Javax.swing
Interface Actiolistener from Java.awt.event
BorderLayout class from java.awt usage: Borderlayout.south/center ... See documentation
Importjavax.swing.*;Importjava.awt.*; Public classPanelextendsjpanel{ Public voidpaintcomponent (Graphics g) {intRed = (int) (Math.random () * 255); intGreen = (int) (Math.random () * 255); intBlue = (int) (Math.random () * 255); Color MyColor=NewColor (Red,green,blue); G.setcolor (MyColor); G.filloval (70,70, 100, 100); }}
View class Panel
Let the panel inherit JPanel, and the Paintcomponent (Graphics g) method that overrides it can draw as you want
Overall thought:
Build a class Touchacol
1 JFrame, Panel (inherited JPanel) and button objects are built separately
Then put the object of the latter two on the JFrame object, set the listener of the button to the object of Touchacol (the object is ActionListener)
So the actionperformed (ActionEvent e) method in interface ActionListener is implemented as an event-handling method in the class of the object (E is the button being pressed)
Deliberately set the frame as an instance variable.
Trigger button to change the small circle color on panel panels