Add action listener to a JButton in Java
Description
The following code shows how to add action listener to a JButton.
Example
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from w ww .j a v a 2s .c o m*/
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame {
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Test");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed");
}
});
getContentPane().add(b);
pack();
}
public static void main(String[] args) {
Main sb = new Main();
sb.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »