Example usage for javax.swing AbstractAction AbstractAction

List of usage examples for javax.swing AbstractAction AbstractAction

Introduction

In this page you can find the example usage for javax.swing AbstractAction AbstractAction.

Prototype

public AbstractAction(String name, Icon icon) 

Source Link

Document

Creates an Action with the specified name and small icon.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    // Retrieve the icon
    Icon icon = new ImageIcon("icon.gif");

    // Create an action with an icon
    Action action = new AbstractAction("Button Label", icon) {
        // This method is called when the button is pressed
        public void actionPerformed(ActionEvent evt) {
            // Perform action
        }/*from  w  w w . ja  v  a  2  s. c  o  m*/
    };

    // Create the button; the icon will appear to the left of the label
    JButton button = new JButton(action);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JToolBar toolbar = new JToolBar();
    ImageIcon icon = new ImageIcon("icon.gif");
    Action action = new AbstractAction("Button Label", icon) {
        public void actionPerformed(ActionEvent evt) {
        }//from w  w  w  .  j  av  a 2 s.  c  o m
    };

    JButton c1 = new JButton(action);
    c1.setText(null);
    c1.setMargin(new Insets(0, 0, 0, 0));
    toolbar.add(c1);

    JToggleButton c2 = new JToggleButton(action);
    c2.setText(null);
    c2.setMargin(new Insets(0, 0, 0, 0));
    toolbar.add(c2);

    JComboBox c3 = new JComboBox(new String[] { "A", "B", "C" });
    c3.setPrototypeDisplayValue("XXXXXXXX"); // Set a desired width
    c3.setMaximumSize(c3.getMinimumSize());
    toolbar.add(c3);
}

From source file:MenuY.java

public static void main(String args[]) {
    ActionListener actionListener = new MenuActionListener();
    MenuKeyListener menuKeyListener = new MyMenuKeyListener();
    ChangeListener cListener = new MyChangeListener();
    MenuListener menuListener = new MyMenuListener();
    MenuSelectionManager manager = MenuSelectionManager.defaultManager();
    manager.addChangeListener(cListener);
    JFrame frame = new JFrame("MenuSample Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuBar bar = new VerticalMenuBar();
    //    JMenuBar bar = new JMenuBar();

    // File Menu, F - Mnemonic
    JMenu file = new JMenu("File");
    file.setMnemonic(KeyEvent.VK_F);
    file.addChangeListener(cListener);/*from  w w  w  .j  a v a2s. c o  m*/
    file.addMenuListener(menuListener);
    file.addMenuKeyListener(menuKeyListener);
    JPopupMenu popupMenu = file.getPopupMenu();
    popupMenu.setLayout(new GridLayout(3, 3));
    bar.add(file);

    // File->New, N - Mnemonic
    JMenuItem newItem = new JMenuItem("New", KeyEvent.VK_N);
    newItem.addActionListener(actionListener);
    newItem.addChangeListener(cListener);
    newItem.addMenuKeyListener(menuKeyListener);
    file.add(newItem);

    // File->Open, O - Mnemonic
    JMenuItem openItem = new JMenuItem("Open", KeyEvent.VK_O);
    openItem.addActionListener(actionListener);
    openItem.addChangeListener(cListener);
    openItem.addMenuKeyListener(menuKeyListener);
    file.add(openItem);

    // File->Close, C - Mnemonic
    JMenuItem closeItem = new JMenuItem("Close", KeyEvent.VK_C);
    closeItem.addActionListener(actionListener);
    closeItem.addChangeListener(cListener);
    closeItem.addMenuKeyListener(menuKeyListener);
    file.add(closeItem);

    // Separator
    file.addSeparator();

    // File->Save, S - Mnemonic
    JMenuItem saveItem = new JMenuItem("Save", KeyEvent.VK_S);
    saveItem.addActionListener(actionListener);
    saveItem.addChangeListener(cListener);
    saveItem.addMenuKeyListener(menuKeyListener);
    file.add(saveItem);

    // Separator
    file.addSeparator();

    // File->Exit, X - Mnemonic
    JMenuItem exitItem = new JMenuItem("Exit", KeyEvent.VK_X);
    exitItem.addActionListener(actionListener);
    exitItem.addChangeListener(cListener);
    exitItem.addMenuKeyListener(menuKeyListener);
    file.add(exitItem);

    // Edit Menu, E - Mnemonic
    JMenu edit = new JMenu("Edit");
    edit.setMnemonic(KeyEvent.VK_E);
    edit.addChangeListener(cListener);
    edit.addMenuListener(menuListener);
    edit.addMenuKeyListener(menuKeyListener);
    bar.add(edit);

    // Edit->Cut, T - Mnemonic, CTRL-X - Accelerator
    JMenuItem cutItem = new JMenuItem("Cut", KeyEvent.VK_T);
    cutItem.addActionListener(actionListener);
    cutItem.addChangeListener(cListener);
    cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.CTRL_MASK));
    cutItem.addMenuKeyListener(menuKeyListener);
    edit.add(cutItem);

    // Edit->Copy, C - Mnemonic, CTRL-C - Accelerator
    JMenuItem copyItem = new JMenuItem("Copy", KeyEvent.VK_C);
    copyItem.addActionListener(actionListener);
    copyItem.addChangeListener(cListener);
    copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK));
    copyItem.addMenuKeyListener(menuKeyListener);
    copyItem.setEnabled(false);
    edit.add(copyItem);

    // Edit->Paste, P - Mnemonic, CTRL-V - Accelerator, Disabled
    JMenuItem pasteItem = new JMenuItem("Paste", KeyEvent.VK_P);
    pasteItem.addActionListener(actionListener);
    pasteItem.addChangeListener(cListener);
    pasteItem.addMenuKeyListener(menuKeyListener);
    pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK));
    pasteItem.setEnabled(false);
    edit.add(pasteItem);

    // Separator
    edit.addSeparator();

    // Edit->Find, F - Mnemonic, F3 - Accelerator
    JMenuItem findItem = new JMenuItem("Find", KeyEvent.VK_F);
    findItem.addActionListener(actionListener);
    findItem.addChangeListener(cListener);
    findItem.addMenuKeyListener(menuKeyListener);
    findItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
    edit.add(findItem);

    // Edit->Options Submenu, O - Mnemonic, at.gif - Icon Image File
    Icon atIcon = new ImageIcon("at.gif");
    Action findAction = new AbstractAction("Options", atIcon) {
        ActionListener actionListener = new MenuActionListener();

        public void actionPerformed(ActionEvent e) {
            actionListener.actionPerformed(e);
        }
    };
    findAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_O));
    JMenuItem jMenuItem = new JMenuItem(findAction);

    JMenu findOptions = new JMenu(findAction);
    findOptions.addChangeListener(cListener);
    findOptions.addMenuListener(menuListener);
    findOptions.addMenuKeyListener(menuKeyListener);

    // ButtonGrou for radio buttons
    ButtonGroup directionGroup = new ButtonGroup();

    // Edit->Options->Forward, F - Mnemonic, in group
    JRadioButtonMenuItem forward = new JRadioButtonMenuItem("Forward", true);
    forward.addActionListener(actionListener);
    forward.addChangeListener(cListener);
    forward.addMenuKeyListener(menuKeyListener);
    forward.setMnemonic(KeyEvent.VK_F);
    findOptions.add(forward);
    directionGroup.add(forward);

    // Edit->Options->Backward, B - Mnemonic, in group
    JRadioButtonMenuItem backward = new JRadioButtonMenuItem("Backward");
    backward.addActionListener(actionListener);
    backward.addChangeListener(cListener);
    backward.addMenuKeyListener(menuKeyListener);
    backward.setMnemonic(KeyEvent.VK_B);
    findOptions.add(backward);
    directionGroup.add(backward);

    // Separator
    findOptions.addSeparator();

    // Edit->Options->Case Sensitive, C - Mnemonic
    JCheckBoxMenuItem caseItem = new JCheckBoxMenuItem("Case Sensitive");
    caseItem.addActionListener(actionListener);
    caseItem.addChangeListener(cListener);
    caseItem.addMenuKeyListener(menuKeyListener);
    caseItem.setMnemonic(KeyEvent.VK_C);
    findOptions.add(caseItem);
    edit.add(findOptions);

    frame.setJMenuBar(bar);
    //    frame.getContentPane().add(bar, BorderLayout.EAST);
    frame.setSize(350, 250);
    frame.setVisible(true);
}

From source file:ToolbarDemo.java

protected JMenuBar createMenuBar() {
    final JMenuBar menuBar = new JMenuBar();

    JMenu mFile = new JMenu("File");
    mFile.setMnemonic('f');

    ImageIcon iconNew = new ImageIcon("file_new.gif");
    Action actionNew = new AbstractAction("New", iconNew) {
        public void actionPerformed(ActionEvent e) {
            System.out.println("new action");
        }/*www.  j ava  2 s.c  o m*/
    };
    JMenuItem item = mFile.add(actionNew);
    mFile.add(item);

    ImageIcon iconOpen = new ImageIcon("file_open.gif");
    Action actionOpen = new AbstractAction("Open...", iconOpen) {
        public void actionPerformed(ActionEvent e) {
            System.out.println("open action");
        }
    };
    item = mFile.add(actionOpen);
    mFile.add(item);

    ImageIcon iconSave = new ImageIcon("file_save.gif");
    Action actionSave = new AbstractAction("Save...", iconSave) {
        public void actionPerformed(ActionEvent e) {
            System.out.println("save action");
        }
    };
    item = mFile.add(actionSave);
    mFile.add(item);

    mFile.addSeparator();

    Action actionExit = new AbstractAction("Exit") {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    };
    item = mFile.add(actionExit);
    item.setMnemonic('x');
    menuBar.add(mFile);

    toolBar = new JToolBar();
    JButton btn1 = toolBar.add(actionNew);
    btn1.setToolTipText("New text");
    JButton btn2 = toolBar.add(actionOpen);
    btn2.setToolTipText("Open text file");
    JButton btn3 = toolBar.add(actionSave);
    btn3.setToolTipText("Save text file");

    ActionListener fontListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            updateMonitor();
        }
    };

    JMenu mFont = new JMenu("Font");
    mFont.setMnemonic('o');

    ButtonGroup group = new ButtonGroup();
    fontMenus = new JMenuItem[FontNames.length];
    for (int k = 0; k < FontNames.length; k++) {
        int m = k + 1;
        fontMenus[k] = new JRadioButtonMenuItem(m + " " + FontNames[k]);
        boolean selected = (k == 0);
        fontMenus[k].setSelected(selected);
        fontMenus[k].setMnemonic('1' + k);
        fontMenus[k].setFont(fonts[k]);
        fontMenus[k].addActionListener(fontListener);
        group.add(fontMenus[k]);
        mFont.add(fontMenus[k]);
    }

    mFont.addSeparator();

    boldMenu.setMnemonic('b');
    Font fn = fonts[1].deriveFont(Font.BOLD);
    boldMenu.setFont(fn);
    boldMenu.setSelected(false);
    boldMenu.addActionListener(fontListener);
    mFont.add(boldMenu);

    italicMenu.setMnemonic('i');
    fn = fonts[1].deriveFont(Font.ITALIC);
    italicMenu.setFont(fn);
    italicMenu.setSelected(false);
    italicMenu.addActionListener(fontListener);
    mFont.add(italicMenu);

    menuBar.add(mFont);

    getContentPane().add(toolBar, BorderLayout.NORTH);

    return menuBar;
}

From source file:ToolBarTest.java

public ToolBarFrame() {
    setTitle("ToolBarTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    // add a panel for color change

    panel = new JPanel();
    add(panel, BorderLayout.CENTER);

    // set up actions

    Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
    Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), Color.YELLOW);
    Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);

    Action exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif")) {
        public void actionPerformed(ActionEvent event) {
            System.exit(0);//from  ww w . j  a  va2 s . c  om
        }
    };
    exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");

    // populate tool bar

    JToolBar bar = new JToolBar();
    bar.add(blueAction);
    bar.add(yellowAction);
    bar.add(redAction);
    bar.addSeparator();
    bar.add(exitAction);
    add(bar, BorderLayout.NORTH);

    // populate menu

    JMenu menu = new JMenu("Color");
    menu.add(yellowAction);
    menu.add(blueAction);
    menu.add(redAction);
    menu.add(exitAction);
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(menu);
    setJMenuBar(menuBar);
}

From source file:org.jcurl.demo.editor.EditorApp.java

/**
 * @param name//from w w w.  j  av a2  s .  c  o  m
 * @param icon
 * @param executor
 * @param action
 * @return the generated action
 */
private static AbstractAction createAction(final String name, final Icon icon, final Object executor,
        final String action) {
    return new AbstractAction(name, icon) {

        private static final long serialVersionUID = 1L;

        private Method m = null;

        public void actionPerformed(final ActionEvent evt) {
            if (m == null)
                try {
                    m = executor.getClass().getMethod(action, null);
                } catch (Exception e) {
                    try {
                        m = executor.getClass().getDeclaredMethod(action, null);
                    } catch (SecurityException e1) {
                        throw new RuntimeException(e1);
                    } catch (NoSuchMethodException e1) {
                        throw new RuntimeException(e1);
                    }
                }
            try {
                m.invoke(executor, null);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    };
}

From source file:org.jcurl.demo.tactics.TacticsApp.java

/**
 * @param name/* w w w. ja  v  a2s. c  o m*/
 * @param icon
 * @param executor
 * @param action
 * @return the generated action
 */
private static AbstractAction createAction(final String name, final Icon icon, final Object executor,
        final String action) {
    return new AbstractAction(name, icon) {
        private static final long serialVersionUID = -6445283333165071107L;

        private Method m = null;

        public void actionPerformed(final ActionEvent evt) {
            if (m == null)
                try {
                    m = executor.getClass().getMethod(action, null);
                } catch (Exception e) {
                    try {
                        m = executor.getClass().getDeclaredMethod(action, null);
                    } catch (SecurityException e1) {
                        throw new RuntimeException(e1);
                    } catch (NoSuchMethodException e1) {
                        throw new RuntimeException(e1);
                    }
                }
            try {
                m.invoke(executor, null);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    };
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopFileMultiUploadField.java

public DesktopFileMultiUploadField() {
    fileUploading = AppBeans.get(FileUploadingAPI.NAME);

    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(true);

    DesktopResources resources = App.getInstance().getResources();
    Messages messages = AppBeans.get(Messages.NAME);
    String caption = messages.getMessage(getClass(), "upload.selectFiles");
    impl = new JButton();
    impl.setAction(new AbstractAction(caption, resources.getIcon(DEFAULT_ICON)) {
        @Override//from w  w  w .java  2s . co  m
        public void actionPerformed(ActionEvent e) {
            if (fileChooser.showOpenDialog(impl) == JFileChooser.APPROVE_OPTION) {
                processFiles(fileChooser.getSelectedFiles());
            }
        }
    });
    DesktopComponentsHelper.adjustSize(impl);
}

From source file:de.dakror.virtualhub.server.ServerFrame.java

public void init() {
    initFiles();/* ww  w . j  a  va  2s  .  co m*/

    logArea = new JTextArea();
    logArea.setWrapStyleWord(true);
    logArea.setEditable(false);
    logArea.setLineWrap(true);
    DefaultCaret caret = (DefaultCaret) logArea.getCaret();
    caret.setSelectionVisible(false);
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

    wrap = new JScrollPane(logArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    setContentPane(wrap);

    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("Aktionen");
    menu.add(new JMenuItem(
            new AbstractAction("Protokoll leeren", new ImageIcon(getClass().getResource("/img/trash.png"))) {
                private static final long serialVersionUID = 1L;

                @Override
                public void actionPerformed(ActionEvent e) {
                    logArea.setText("");
                    log("Protokoll geleert.");
                }
            }));
    menu.add(logEnabled = new JCheckBoxMenuItem("Protokoll aktiviert",
            new ImageIcon(getClass().getResource("/img/log.png")), true));
    menu.add(packetLogEnabled = new JCheckBoxMenuItem("Paketverkehr protokollieren",
            new ImageIcon(getClass().getResource("/img/traffic.png")), false));
    menu.addSeparator();
    menu.add(new JMenuItem(new AbstractAction("Backup-Einstellungen",
            new ImageIcon(getClass().getResource("/img/backup_edit.png"))) {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                BackupEditDialog.show();
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
    }));

    menuBar.add(menu);
    setJMenuBar(menuBar);
}

From source file:org.nuclos.client.customcomp.resplan.ResPlanPanel.java

public ResPlanPanel(ResPlanController cntrl, CollectableResPlanModel model, DateTimeModel timeModel) {
    final SpringLocaleDelegate localeDelegate = SpringLocaleDelegate.getInstance();

    this.controller = cntrl;
    this.timeModel = timeModel;
    this.resPlanModel = model;
    setLayout(new BorderLayout());

    JToolBar tb = UIUtils.createNonFloatableToolBar();
    tb.setFloatable(false);// w w w  .j a v  a  2s .c om
    tb.add(new AbstractAction(localeDelegate.getText("nuclos.resplan.action.refresh"),
            Icons.getInstance().getIconRefresh16()) {

        @Override
        public void actionPerformed(ActionEvent e) {
            controller.refresh();
        }
    });
    tb.add(exportAction);
    tb.addSeparator();

    this.timeHorizon = new Interval<Date>(model.getDefaultViewFrom(), model.getDefaultViewUntil());

    final LabeledComponentSupport support = new LabeledComponentSupport();
    startDateChooser = new DateChooser(support, timeHorizon.getStart());
    startDateChooser.setMinimumSize(startDateChooser.getPreferredSize());
    startDateChooser.setMaximumSize(startDateChooser.getPreferredSize());
    endDateChooser = new DateChooser(support, timeHorizon.getEnd());
    endDateChooser.setMinimumSize(endDateChooser.getPreferredSize());
    endDateChooser.setMaximumSize(endDateChooser.getPreferredSize());

    tb.add(new JLabel(localeDelegate.getText("nuclos.resplan.toolbar.from")));
    tb.add(startDateChooser);
    tb.add(Box.createHorizontalStrut(5));
    tb.add(new JLabel(localeDelegate.getText("nuclos.resplan.toolbar.until")));
    tb.add(endDateChooser);

    timeGranularityModel = new ListComboBoxModel<ResPlanController.TimeGranularity>(
            controller.getTimeGranularityOptions());
    tb.addSeparator();
    tb.add(new JLabel(localeDelegate.getText("nuclos.resplan.toolbar.granularity")));
    timeGranularityComboBox = new JComboBox(timeGranularityModel);
    tb.add(timeGranularityComboBox);
    timeGranularityComboBox
            .setMaximumSize(Orientation.VERTICAL.updateExtent(timeGranularityComboBox.getPreferredSize(), 20));

    tb.addSeparator();
    tb.add(new JLabel(localeDelegate.getText("nuclos.resplan.toolbar.resourceFilter")));
    searchFilterComboBox = new JComboBox();
    searchFilterComboBox.setRenderer(new SearchFilterListCellRenderer());
    refreshSearchFilter();
    tb.add(searchFilterComboBox);
    searchFilterComboBox
            .setMaximumSize(Orientation.VERTICAL.updateExtent(searchFilterComboBox.getPreferredSize(), 20));

    tb.add(Box.createGlue());

    infoButton = new JButton(infoAction);
    infoButton.setVisible(false);
    tb.add(infoButton);

    tb.add(Box.createHorizontalStrut(3));

    initJResPlan();

    ActionListener dateChooserListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            timeHorzionChanged();
        }
    };
    startDateChooser.addActionListener(dateChooserListener);
    endDateChooser.addActionListener(dateChooserListener);

    timeGranularityComboBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                Runnable runnable = createScrollToCurrentAreaRunnable();
                ResPlanController.TimeGranularity granularity = timeGranularityModel.getSelectedItem();
                resPlan.setTimeModel(granularity.getTimeModel());
                resPlan.getTimelineHeader().setCategoryModel(granularity.getHeaderCategories());
                SwingUtilities.invokeLater(runnable);
            }
        }
    });
    searchFilterComboBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                EntitySearchFilter filter = (EntitySearchFilter) searchFilterComboBox.getSelectedItem();
                if (filter instanceof NewCustomSearchFilter) {
                    runCustomSearch();
                    return;
                }
                setSearchCondition(filter.getSearchCondition());
            }
        }
    });

    scrollPane = new JScrollPane(resPlan);

    JButton corner = new JButton(switchOrientationAction);
    corner.setBorderPainted(false);
    scrollPane.setCorner(JScrollPane.LOWER_RIGHT_CORNER, corner);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    add(tb, BorderLayout.NORTH);
    add(scrollPane, BorderLayout.CENTER);

    resPlan.setTimeHorizon(this.timeHorizon);
    resPlan.invalidate();

    setFocusable(true);
    setFocusCycleRoot(true);
    getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("DELETE"), "delete");
    //getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("control F"), "find");
    getActionMap().put("delete", removeAction);
    //getActionMap().put("find", findAction);
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.ACTIVATE_SEARCH_PANEL_2, findAction, this);
}