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.

Create a JButton Component from Action in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer