After using swing to design a graphical interface, you must use event-handling mechanisms to enable our interface to handle events. This can be counted as a complete app. The swing event handling mechanism is to take a delegated event model, which is referred to as when an event occurs. The object that produces the event, puts the event information. A way to pass to listeners for processing. The event information described here is actually the object created by a class in the Java.awt.event event class library. Say you clicked on a button. This button if the use of event monitoring, it will trigger an event, and then delegate time to the time to listen to handle simple event monitoring, when clicking on the Red button, the panel turns red, when you click the Blue button panel into the blue package draws;import java.awt.*; Import Javax.swing.*;import Java.awt.event.*;import Java.awt.event.actionevent;import java.awt.event.actionlistener; /** Swing Event monitoring, processing learning * Created by admin on 2017/7/22.*/public class events extends JFrame implements actionlistener{//we need to implement ActionListener method actionperformed Complete Event listening process private JPanel panel;private JButton jButton1, jbutton2;public static void Main (string[] args) {Events events = new events (); Public Events () {panel = new JPanel (); jButton1 = new JButton ("Switch to red") JButton2 = new JButton ("Switch to Blue"); This.add (JButton1, B Orderlayout.north); This.add (panel, borderlayout.center); This.add (JButton2, Borderlayout.south);//register for monitoring, monitoring, parameter is who wants to be handled here I let our events class to handle the listener, so fill this out to represent the class itself Jbutton1.addactionlistener (This)///Specify the action command to pass this command to listener Jbutton1.setactioncommand ("Red"); Jbutton2.addactionlistener (this); Jbutton2.setactioncommand ("Blue"); This.settitle ("Event handling"); This.setlocation (+); this.setsize (800, 600); This.setvisible (True); this.setresizable (false); this.setdefaultcloseoperation (jframe.exit_on_close);} public void actionperformed (ActionEvent e) {//Handles the event, judging which button is clicked if (E.getactioncommand (). Equals ("Red")) { Panel.setbackground (color.red);} if (E.getactioncommand (). Equals ("Blue")) {Panel.setbackground (Color.Blue);}}
Java GUI programming (swing) seven swing event listener