The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing  [141 examples] > Actions  [3 examples]

e857. Enabling an Action

Actions can be bound to many different kinds of components. When an action is enabled or disabled, components that are bound to that action may automatically alter its display to match the enabled state of the action. This example creates three components: a button, a text component, and a menu item - - all bound to the same action. When the action is disabled, the button and menu item will appear disabled and the text component will not be able to invoke the action.
    JFrame frame = new JFrame();
    
    // Button
    JButton button = new JButton(action);
    
    // Text Component
    JTextField textfield = new JTextField();
    textfield.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke("F2"), action.getValue(Action.NAME));
    textfield.getActionMap().put(action.getValue(Action.NAME), action);
    
    // Menu Item
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("Menu Label");
    menu.add(new JMenuItem(action));
    menuBar.add(menu);
    frame.setJMenuBar(menuBar);
    
    // The action
    public Action action = new AbstractAction("Action Name") {
        public void actionPerformed(ActionEvent evt) {
            // Perform action
        }
    };

 Related Examples
e855. Creating an Action
e856. Listing the Actions in a Component

See also: JButton    JCheckBox    JComboBox    JDesktop and JInternalFrame    JFrame, JWindow, JDialog    JLabel    JList    JProgressBar    JRadioButton    JScrollPane    JSlider    JSpinner    JSplitPane    JTabbedPane    JToolBar    Keystrokes and Input Maps    Layout    Look and Feel    Menus    Progress Monitor    The Screen    Tool Tips    UI Default Values   


© 2002 Addison-Wesley.