The swing component in Java, where the focus of the button is to listen for events, can be called by JButton's addActionListener () method. This method takes an object that implements the ActionListener interface as a parameter, and the ActionListener interface contains only a actionperformed () method, so if you want to associate the code of the event handling with JButton, There are three ways to do this:
The first type:
public class Button extends MyFrame {
Private JButton
B1 = new JButton ("Button1"),
b2 = new JButton ("Button2");
Private JTextField txt = new JTextField (10);
Class Buttonlistener implements actionlistener{//define inner class to implement event monitoring
public void actionperformed (ActionEvent e) {
Txt.settext (((JButton) E.getsource ()). GetText ());
/*
* String name = ((JButton) E.getsource ()). GetText ();
* Txt.settext (name);
*/
}
}
Private Buttonlistener B = new Buttonlistener ();
Public Button () {
B1.addactionlistener (b);
B2.addactionlistener (b);
This.setlayout (New FlowLayout ());
This.add (B1);
This.add (B2);
This.add (TXT);
}
public static void Main (string[] args) {
Swingutilities.invokelater (New Runnable () {
public void Run () {
New Button ();
}
});
}
}
The second type:
Object B of the ActionListener class is created directly, using an anonymous inner class
Private ActionListener b= New ActionListener () {//define inner classes to implement event snooping
public void actionperformed (ActionEvent e) {
Txt.settext (((JButton) E.getsource ()). GetText ());
/*
* String name = ((JButton) E.getsource ()). GetText ();
* Txt.settext (name);
*/
}
};
The third type:
Create a button's listener directly in the program without the need to introduce a listener
B1.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent e) {
Txt.settext (((JButton) E.getsource ()). GetText ());
}
});
B2.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent e) {
Txt.settext ("");
}
});
Three ways to listen for button events in Java