1. Event monitoring
Test code 1:
package cn.javastudy.summary;import java.awt.*;import java.awt.event.*;public class TestTextField { public static void main(String args[]) { new MyFrameTextField(); }}class MyFrameTextField extends Frame { MyFrameTextField() { TextField tf = new TextField(); add(tf); tf.addActionListener(new Monitor3()); tf.setEchoChar('*'); /* * This setEchoChar() method is to set the characters displayed when inputting in the text box. Here it is set to *, so that any input content will be displayed as *, but you can still see the input content when printing out */ setVisible(true); pack(); }}class Monitor3 implements ActionListener { /* * All methods in the interface are public (public) * So when copying void actionPerformed(ActionEvent e) from the API document, you must add public in front of void */ public void actionPerformed(ActionEvent e) { /* The relevant information of the event is encapsulated in object e. The relevant information of the event can be obtained through the relevant methods of object e*/ TextField tf = (TextField) e.getSource(); /* * getSource() method is to get the event source. Note: when you get this event source, * treat it as the parent class of TextField. The definition of the getSource() method is: "public Object getSource()" return value is an Object object, * So you must cast it to an object of type TextField* If you want to access the event source object of another class in one class, you can use the getSource() method */ System.out.println(tf.getText());// tf.getText() is to get the content in the text box tf.setText("");// Clear the content in the text box }} Test code 2:
package cn.javastudy.summary;import java.awt.*;import java.awt.event.*;public class TestActionEvent2{ public static void main(String args[]){ Frame f = new Frame("TestActionEvent"); Button btn1 = new Button("start"); Button btn2 = new Button("stop"); Monitor2 m2 = new Monitor2();//Create the listening object btn1.addActionListener(m2); /*A listening object listens for the actions of two buttons at the same time*/ btn2.addActionListener(m2); btn2.setActionCommand("GameOver");//Set the return information after executing the click command of btn2 f.add(btn1,BorderLayout.NORTH); f.add(btn2,BorderLayout.CENTER); f.pack(); f.setVisible(true); }}class Monitor2 implements ActionListener{ public void actionPerformed(ActionEvent e){ System.out.println("a button has been pressed,"+"the relative info is:/n"+e.getActionCommand()); /* Use the returned listening object e to call the getActionCommand() method to obtain the return information after the two buttons execute the click command. According to the different returns information, which button is the current operation. btn1 does not use the setActionCommand() method to set, so the information returned by btn1 is the text displayed on the button*/ }}2. TextField event monitoring
Test code:
package cn.javastudy.summary;import java.awt.*;import java.awt.event.*;public class TestTextField { public static void main(String args[]) { new MyFrameTextField(); }}class MyFrameTextField extends Frame { MyFrameTextField() { TextField tf = new TextField(); add(tf); tf.addActionListener(new Monitor3()); tf.setEchoChar('*'); /* * This setEchoChar() method is to set the characters displayed when inputting in the text box. Here it is set to *, so that any input content will be displayed as *, but you can still see the input content when printing out */ setVisible(true); pack(); }}class Monitor3 implements ActionListener { /* * All methods in the interface are public (public) * So when copying void actionPerformed(ActionEvent e) from the API document, you must add public in front of void */ public void actionPerformed(ActionEvent e) { /* The relevant information of the event is encapsulated in object e. The relevant information of the event can be obtained through the relevant methods of object e*/ TextField tf = (TextField) e.getSource(); /* * getSource() method is to get the event source. Note: when you get this event source, * treat it as the parent class of TextField. The definition of the getSource() method is: "public Object getSource()" return value is an Object object, * So you must cast it to an object of type TextField* If you want to access the event source object of another class in one class, you can use the getSource() method */ System.out.println(tf.getText());// tf.getText() is to get the content in the text box tf.setText("");// Clear the content in the text box }} Implementing a simple calculator using TextField class
package cn.javastudy.summary;import java.awt.*;import java.awt.event.*;public class TestMath { public static void main(String args[]) { new TFFrame(); }}/* Here is mainly to complete the layout of the calculator elements*/class TFFrame extends Frame { TFFrame() { /* * Create 3 text boxes and specify their initial sizes to be 10 characters and 15 characters respectively. Here is another construction method of the TextField class public TextField(int columns) */ TextField num1 = new TextField(10); TextField num2 = new TextField(10); TextField num3 = new TextField(15); /* Create an equal sign button*/ Button btnEqual = new Button("="); btnEqual.addActionListener(new MyMonitor(num1, num2, num3)); /* Add a listener to the equal sign button so that a response event occurs after clicking the button*/ Label lblPlus = new Label("+"); /* "+" is a static text, so use the Label class to create a static text object*/ setLayout(new FlowLayout()); /* Change the default BorderLayout layout of Frame to FlowLayout layout*/ add(num1); add(lblPlus); add(num2); add(btnEqual); add(num3); pack(); setVisible(true); }}class MyMonitor implements ActionListener { TextField num1, num2, num3; /* * In order to enable the listening of buttons to work on text boxes, * Therefore, three TextField objects in the custom class MyMonitor are defined in num1, num2, num3, * It also defines a constructor method of the MyMonitor class. This constructor method has three parameters of TextField type, * is used to receive three parameters of TextField type passed from the TFFrame class* Then assign the received three parameters of TextField type to the three parameters of TextField type declared in this class. Then process num1, num2, num3 in the actionPerformed() method */ public MyMonitor(TextField num1, TextField num2, TextField num3) { this.num1 = num1; this.num2 = num2; this.num3 = num3; } public void actionPerformed(ActionEvent e) { /* The relevant information of the event is encapsulated in object e. The relevant information of the event can be obtained through the relevant methods of object e*/ int n1 = Integer.parseInt(num1.getText());/* num1 object calls the getText() method to obtain the text string displayed by itself*/ int n2 = Integer.parseInt(num2.getText());/* num2 object calls the getText() method to obtain the text string displayed by itself*/ num3.setText("" + (n1 + n2));/* num3 object calls the setText() method to set its own display text*/ num1.setText(""); /* After the calculation is completed, clear the contents of the num1 and num2 text boxes */ num2.setText(""); // num3.setText(String.valueOf((n1+n2))); /* When strings are connected with any type of data using "+", the string must be a string. * Here is an empty string and an int type number, so that the int type number obtained by (n1+n2) can be directly converted into a string. * This is a small trick to convert other basic data types into strings. * You can also use "String.valueOf((n1+n2))" to convert the sum of (n1+n2) into a string */ }} Classic usage in JAVA: Holding references to another class in one class
package cn.javastudy.summary;import java.awt.*;import java.awt.event.*;public class TestMath1 { public static void main(String args[]) { new TTMyFrame().launchFrame(); /* Create the TTMyFrame object and call the lauchFrame() method to display the calculator form*/ }}/* Make the form interface of the calculator*/class TTMyFrame extends Frame { /* Encapsulate the code designing the calculator form into a method*/ TextField num1, num2, num3; public void launchFrame() { num1 = new TextField(10); num2 = new TextField(15); num3 = new TextField(15); Label lblPlus = new Label("+"); Button btnEqual = new Button("="); btnEqual.addActionListener(new MyMonitorbtnEqual(this)); setLayout(new FlowLayout()); add(num1); add(lblPlus); add(num2); add(btnEqual); add(num3); pack(); setVisible(true); }}/* * Here, by obtaining a reference to the TTMyFrame class, and then using this reference to access the member variables in the TTMyFrame class* This approach is much better than the previous method to directly access the member variables in the TTMyFrame class, * Now you need to access the member variables in the TTMyFrame class, and you can directly access the member variables in the TTMyFrame class object. * This TTMyFrame class object is like a big housekeeper, and I told the big housekeeper that I want to access the member variables in the TTMyFrame class, * The big housekeeper's reference will help me find it, and I no longer need to find it myself. * This usage of holding references to another class in one class is a very typical usage* Use the obtained reference to access all members of another class in one class*/class MyMonitorbtnEqual implements ActionListener { TTMyFrame ttmf = null; public MyMonitorbtnEqual(TTMyFrame ttmf) { this.ttmf = ttmf; } public void actionPerformed(ActionEvent e) { int n1 = Integer.parseInt(ttmf.num1.getText()); int n2 = Integer.parseInt(ttmf.num2.getText()); ttmf.num3.setText("" + (n1 + n2)); ttmf.num1.setText(""); ttmf.num2.setText(""); }}The operation results are as follows:
III. Internal Class
Examples of internal classes:
package cn.javastudy.summary;import java.awt.*;import java.awt.event.*;public class TestMath3 { public static void main(String args[]) { new MyMathFrame().launchFrame(); }}class MyMathFrame extends Frame { TextField num1, num2, num3; public void launchFrame() { num1 = new TextField(10); num2 = new TextField(15); num3 = new TextField(15); Label lblPlus = new Label("+"); Button btnEqual = new Button("="); btnEqual.addActionListener(new MyMonitor()); setLayout(new FlowLayout()); add(num1); add(lblPlus); add(num2); add(btnEqual); add(num3); pack(); setVisible(true); } /* * This MyMonitor class is an inner class, which defines the MyFrame class in the MyFrame class called the wrapper class*/ /* * The benefits of using inner classes: * The first huge benefit is that it can access all member variables and methods of the external class (i.e., the wrapper class of the inner class) without any obstacles* For example, the three member variables num1, num2, num3 defined in the MyFrame class (external class), * You can directly access it in MyMonitor (inner class)* This is equivalent to the internal class object having a reference to the external class object by default when creating an external class object*/ private class MyMonitor implements ActionListener { public void actionPerformed(ActionEvent e) { int n1 = Integer.parseInt(num1.getText()); int n2 = Integer.parseInt(num2.getText()); num3.setText("" + (n1 + n2)); num1.setText(""); num2.setText(""); } }}The huge benefits of internal classes are:
4. Graphics
Test code:
package cn.javastudy.summary;import java.awt.*;public class TestPaint{ public static void main(String args[]){ new MyPaint().launchFrame(); /*The paint(Graphics g) method is not displayed in the main() method, but after creating the Frame form, you can see that circles and rectangles are drawn on the Frame form. This is because the paint() method is a special method. It will automatically call implicitly when creating the Frame form. When we minimize the Frame form and open it again, we will call the paint() method again and draw the circles and rectangles on the Frame form. That is, every time we need to repaint the Frame form, the paint() method will be automatically called*/ }}class MyPaint extends Frame{ public void launchFrame(){ setBounds(200,200,640,480); setVisible(true); } public void paint(Graphics g){ /*paint(Graphics g) method has a Graphics type parameter g We can treat this g as a painter, the painter holds a brush in his hand, and we draw the various images we want by setting the color and shape of the brush */ /*Set the color of the brush */ g.setColor(Color.red); g.fillOval(100,100,100,100);/*Draw a solid ellipse*/ g.setColor(Color.green); g.fillRect(150,200,200);/*Draw a solid rectangle*//*The two lines of code below are written for good programming habits in writing programs. Now you should restore the initial color of the brush, which is equivalent to cleaning the color on the brush after the painter has used up the brush*/ Color c = g.getColor(); g.setColor(c); }}Running results:
5. Mouse event adapter
Test code:
package cn.galc.test;import java.awt.*;import java.awt.event.*;import java.util.*;public class MyMouseAdapter{ public static void main(String args[]) { new MyFrame("drawing..."); }}class MyFrame extends Frame { ArrayList points = null; MyFrame(String s) { super(s); points = new ArrayList(); setLayout(null); setBounds(300,300,400,300); this.setBackground(new Color(204,204,255)); setVisible(true); this.addMouseListener(new Monitor()); } public void paint(Graphics g) { Iterator i = points.iterator(); while(i.hasNext()){ Point p = (Point)i.next(); g.setColor(Color.BLUE); g.fillOval(px,py,10,10); } } public void addPoint(Point p){ points.add(p); }}class Monitor extends MouseAdapter { public void mousePressed(MouseEvent e) { MyFrame f = (MyFrame)e.getSource(); f.addPoint(new Point(e.getX(),e.getY())); f.repaint(); }}6. Windows Event
Test code:
package cn.galc.test;import java.awt.*;import java.awt.event.*;public class TestWindowClose{ public static void main(String args[]){ new WindowFrame("Close WindowFrame"); }}class WindowFrame extends Frame{ public WindowFrame(String s){ super(s); setBounds(200,200,400,300); setLayout(null); setBackground(new Color(204,204,255)); setVisible(true); this.addWindowListener(new WindowMonitor());/* Listen to the actions of this form, encapsulate all the action information into an object and pass it into the listening class*/ this.addWindowListener( /*Define a class in a method, this class is called a local class, also called anonymous internal class. The code here is very similar to the body of a class, but this class has no name, so it is called anonymous class here to use this anonymous class as a WindowAdapter class. The essential meaning of this syntax is equivalent to the inheritance of this anonymous class from the WindowAdapter class. Now new anonymous class object comes out and then treats this object as a WindowAdapter to use this anonymous class after () and no one knows it*/ new WindowAdapter(){ public void windowClosing(WindowEvent e){ setVisible(false); System.exit(-1); } } ); } /*The listening class is also defined as an internal class*/ class WindowMonitor extends WindowAdapter{ /*WindowAdapter (Window Adapter) class implements the WindowListener listening interface. Rewrites all methods in the WindowListener interface. If you directly use the custom WindowMonitor class to directly implement the WindowListener interface, you have to rewrite all methods in the WindowListener interface. But now you only need to use one of these methods. Therefore, you can inherit a subclass of the WindowListener listening interface and rewrite the method you need to use in this subclass. This method is much simpler and more convenient than directly implementing the WindowListener listening interface. */*Rewrites the windowClosing(WindowEvent e) method that needs to be used*//*Public void windowClosing(WindowEvent e){ setVisible(false);/*Set the form to not display, and the form is closed*/ System.exit(0);/*Exit normally*/ } }}7. Keyboard response event - KeyEvent
Test code:
package cn.galc.test;import java.awt.*;import java.awt.event.*;public class TestKeyEvent{ public static void main(String args[]){ new KeyFrame("Keyboard response event"); }}class KeyFrame extends Frame{ public KeyFrame(String s){ super(s); setBounds(200,200,400,300); setLayout(null); setVisible(true); addKeyListener(new KeyMonitor()); } /*Define the custom keyboard listening class as an internal class. This listening class inherits from the keyboard adapter KeyAdapter class. Inherits from the KeyAdapter class. In order to be concise and convenient, you only need to rewrite the methods you need to use. This method is simpler and more convenient than directly implementing the KeyListener interface. If you directly implement the KeyListener interface, you have to rewrite all the methods in the KeyListener interface, but only one method is really used. In this way, rewriting other methods but not using them will inevitably do useless work*/ class KeyMonitor extends KeyAdapter{ public void keyPressed(KeyEvent e){ int keycode = e.getKeyCode(); /*Use getKeyCode() method to get the virtual code of the key*/ /*If the virtual code of the obtained key is equal to the virtual code of the up key, it means that the currently pressed key is the up key KeyEvent.VK_UP means that the virtual code of obtaining the up key. Each key in the keyboard corresponds to a virtual code. These virtual codes are defined as static constants in the KeyEvent class. Therefore, you can use the form of "class name.static constant name" to access these static constants*/ if(keycode == KeyEvent.VK_UP){ System.out.println("You press the up key"); } } }}/*The keyboard handles events like this: each key corresponds to a virtual code. When a certain key is pressed, the system will find the virtual code corresponding to this key to determine which key is currently pressed*/Through this article, I learned GUI programming with you. I hope you will have a more comprehensive understanding of GUI programming. There are more than this about GUI programming, and you need to continue learning.