Create a JButton Component from Action in Java
Description
The following code shows how to create a JButton Component from Action.
Example
import java.awt.event.ActionEvent;
//from w w w . ja v a2 s .c om
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame {
public Main() {
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Action action = new AbstractAction("Button Label") {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action...
}
};
// Create the button from the action
JButton button = new JButton(action);
add(button);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »