Java Action disable action to disable component
import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JToolBar; public class Main extends JFrame { public static final String ENABLE = "ENABLE"; public static final String DISABLE = "DISABLE"; private JToolBar toolBar = new JToolBar(); private JMenuBar menuBar = new JMenuBar(); private JMenu testMenu = new JMenu("Test"); private MyAction theAction = new MyAction(); private JMenuItem disableActionItem = new JMenuItem("Disable the Action"); public Main() { this.setJMenuBar(menuBar); menuBar.add(testMenu);//from w ww. j a v a2 s . c o m testMenu.add(theAction); toolBar.add(theAction); disableActionItem.setActionCommand(DISABLE); testMenu.add(disableActionItem); disableActionItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(DISABLE)) { theAction.setEnabled(false); disableActionItem.setText("Enable the Action"); disableActionItem.setActionCommand(ENABLE); } else { theAction.setEnabled(true); disableActionItem.setText("Disable the Action"); disableActionItem.setActionCommand(DISABLE); } } }); this.getContentPane().add(toolBar, BorderLayout.NORTH); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(320, 200); this.setVisible(true); } public static void main(String[] args) { Main t = new Main(); } } class MyAction extends AbstractAction { public MyAction() { super("Change Color"); } public void actionPerformed(ActionEvent e) { System.out.println("action"); } }