Example usage for javax.swing KeyStroke getKeyStroke

List of usage examples for javax.swing KeyStroke getKeyStroke

Introduction

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

Prototype

public static KeyStroke getKeyStroke(int keyCode, int modifiers) 

Source Link

Document

Returns a shared instance of a KeyStroke, given a numeric key code and a set of modifiers.

Usage

From source file:edu.harvard.mcz.imagecapture.MainFrame.java

/**
 * This method initializes jMenuItem1   
 *    /*from www  .j a v a  2  s  .  co  m*/
 * @return javax.swing.JMenuItem   
 */
private JMenuItem getJMenuItemCopy() {
    if (jMenuItemCopy == null) {
        jMenuItemCopy = new JMenuItem(new DefaultEditorKit.CopyAction());
        jMenuItemCopy.setText("Copy");
        jMenuItemCopy.setMnemonic(KeyEvent.VK_C);
        jMenuItemCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
        jMenuItemCopy.setEnabled(true);

    }
    return jMenuItemCopy;
}

From source file:io.heming.accountbook.ui.MainFrame.java

private void initMenuBar() {
    JMenuBar menuBar = new JMenuBar();

    // File menu/*from  w w  w .  j  a v a  2s  .c  o m*/
    fileMenu = new JMenu("(F)");
    fileMenu.setMnemonic('F');

    exportMenuItem = new JMenuItem("(B)...");
    exportMenuItem.setIcon(new ImageIcon(getClass().getResource("database-save.png")));
    exportMenuItem.setMnemonic('B');
    exportMenuItem.addActionListener(e -> exportRecords());
    fileMenu.add(exportMenuItem);

    importMenuItem = new JMenuItem("??(R)...");
    importMenuItem.setIcon(new ImageIcon(getClass().getResource("document-import-2.png")));
    importMenuItem.setMnemonic('R');
    importMenuItem.addActionListener(e -> importRecords());
    fileMenu.add(importMenuItem);

    fileMenu.addSeparator();

    quitMenuItem = new JMenuItem("(X)");
    quitMenuItem.setIcon(new ImageIcon(getClass().getResource("application-exit-2.png")));
    quitMenuItem.setMnemonic('X');
    quitMenuItem.addActionListener(e -> quit());
    fileMenu.add(quitMenuItem);

    // View menu
    viewMenu = new JMenu("(V)");
    viewMenu.setMnemonic('V');

    searchMenuItem = new JMenuItem("?(S)");
    searchMenuItem.setIcon(new ImageIcon(getClass().getResource("edit-find-5.png")));
    searchMenuItem.setMnemonic('S');
    searchMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
    searchMenuItem.addActionListener(e -> searchRecords());
    viewMenu.add(searchMenuItem);

    keywordMenuItem = new JMenuItem("(K)");
    keywordMenuItem.setIcon(new ImageIcon(getClass().getResource("text-field.png")));
    keywordMenuItem.setMnemonic('K');
    keywordMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK));
    keywordMenuItem.addActionListener(e -> {
        keywordTextField.requestFocus();
        keywordTextField.selectAll();
    });
    viewMenu.add(keywordMenuItem);

    viewMenu.addSeparator();

    prevPageMenuItem = new JMenuItem("?(P)");
    prevPageMenuItem.setIcon(new ImageIcon(getClass().getResource("go-previous-2.png")));
    prevPageMenuItem.setMnemonic('P');
    prevPageMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.CTRL_MASK));
    prevPageMenuItem.addActionListener(e -> prevPage());
    viewMenu.add(prevPageMenuItem);

    nextPageMenuItem = new JMenuItem("(N)");
    nextPageMenuItem.setIcon(new ImageIcon(getClass().getResource("go-next-2.png")));
    nextPageMenuItem.setMnemonic('N');
    nextPageMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.CTRL_MASK));
    nextPageMenuItem.addActionListener(e -> nextPage());
    viewMenu.add(nextPageMenuItem);

    firstPageMenuItem = new JMenuItem("(F)");
    firstPageMenuItem.setIcon(new ImageIcon(getClass().getResource("go-first.png")));
    firstPageMenuItem.setMnemonic('F');
    firstPageMenuItem
            .setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.SHIFT_MASK + Event.CTRL_MASK));
    firstPageMenuItem.addActionListener(e -> firstPage());
    viewMenu.add(firstPageMenuItem);

    lastPageMenuItem = new JMenuItem("(L)");
    lastPageMenuItem.setIcon(new ImageIcon(getClass().getResource("go-last.png")));
    lastPageMenuItem.setMnemonic('L');
    lastPageMenuItem
            .setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.SHIFT_MASK + Event.CTRL_MASK));
    lastPageMenuItem.addActionListener(e -> lastPage());
    viewMenu.add(lastPageMenuItem);

    // Edit menu
    editMenu = new JMenu("(E)");
    editMenu.setMnemonic('E');

    addRecordMenuItem = new JMenuItem("(A)...");
    addRecordMenuItem.setIcon(new ImageIcon(getClass().getResource("edit-add-3.png")));
    addRecordMenuItem.setMnemonic('A');
    addRecordMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, Event.CTRL_MASK));
    addRecordMenuItem.addActionListener(e -> showAddRecordDialog());
    editMenu.add(addRecordMenuItem);

    //        deleteRecordMenuItem = new JMenuItem("(D)");
    //        deleteRecordMenuItem.setIcon(new ImageIcon(getClass().getResource("edit-delete-6.png")));
    //        deleteRecordMenuItem.setMnemonic('D');
    //        deleteRecordMenuItem.addActionListener(e -> deleteRecord());
    //        editMenu.add(deleteRecordMenuItem);

    editMenu.addSeparator();

    categoryMenuItem = new JMenuItem("???(T)...");
    categoryMenuItem.setIcon(new ImageIcon(getClass().getResource("view-list-icons-2.png")));
    categoryMenuItem.setMnemonic('T');
    categoryMenuItem.addActionListener(e -> showCategoryDialog());
    editMenu.add(categoryMenuItem);

    // Help menu
    helpMenu = new JMenu("(H)");
    helpMenu.setMnemonic('H');

    helpMenuItem = new JMenuItem("(I)");
    helpMenuItem.setIcon(new ImageIcon(getClass().getResource("help-2.png")));
    helpMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
    helpMenuItem.setMnemonic('I');
    helpMenuItem.addActionListener(e -> help());
    helpMenu.add(helpMenuItem);

    aboutMenuItem = new JMenuItem("(A)");
    aboutMenuItem.setIcon(new ImageIcon(getClass().getResource("help-about-2.png")));
    aboutMenuItem.setMnemonic('A');
    aboutMenuItem.addActionListener(e -> about());
    helpMenu.add(aboutMenuItem);

    // Add menu to menu bar
    menuBar.add(fileMenu);
    menuBar.add(editMenu);
    menuBar.add(viewMenu);
    menuBar.add(helpMenu);
    setJMenuBar(menuBar);
}

From source file:com.all.login.view.NewAccountFormPanel.java

JTextField getEmailTextField() {
    if (emailTextField == null) {
        emailTextField = new JTextField();
        emailTextField.setBounds(EMAIL_TEXTFIELD_BOUNDS);
        emailTextField.setSelectionColor(COLOR_SELECTION_TEXTFIELDS);
        emailTextField.setName(EMAIL_TEXT_FIELD_NAME);
        final LowercaseFocusListener emailListener = new LowercaseFocusListener(emailTextField,
                EMAIL_FIELD_NAME);//from   w ww.j  a v  a 2 s . co  m
        emailTextField.addFocusListener(emailListener);
        emailTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                int caretPosition = emailTextField.getCaretPosition();
                if (emailTextField.getName().startsWith(INVALID_FIELD_NAME)) {
                    emailListener.focusLost(null);
                }
                validateAllUserData();
                emailTextField.setCaretPosition(caretPosition);
            }
        });
        InputMap map = emailTextField.getInputMap(JTextField.WHEN_FOCUSED);
        map.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.VK_CONTROL), null);
        emailTextField.addKeyListener(new CopyPasteKeyAdapterForMac());
    }
    return emailTextField;
}

From source file:at.becast.youploader.gui.FrmMain.java

public void initMenuBar() {
    JMenuBar mnuBar = new JMenuBar();
    JMenu mnuFile = new JMenu();
    JMenuItem mnuQuit = new JMenuItem();
    mnuAcc = new JMenu();

    mnuFile.setText(LANG.getString("frmMain.menu.File"));

    mnuQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
    mnuQuit.setText(LANG.getString("frmMain.menu.Quit"));
    mnuQuit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            mnuQuitActionPerformed();//from  w w  w.j  av  a  2  s. co m
        }
    });
    mnuFile.add(mnuQuit);

    mnuBar.add(mnuFile);

    mnuAcc.setText(LANG.getString("frmMain.menu.Account"));
    mnuBar.add(mnuAcc);

    JSeparator separator = new JSeparator();
    JMenuItem mntmAddAccount = new JMenuItem(LANG.getString("frmMain.menu.AddAccount"));
    mntmAddAccount.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            mntmAddAccountActionPerformed();
        }
    });
    mnuAcc.add(mntmAddAccount);
    mnuAcc.add(separator);

    JMenu mnLanguage = new JMenu("Language");
    mnLanguage.setVisible(false);
    mnLanguage.setEnabled(false);
    mnuBar.add(mnLanguage);

    JMenu menu = new JMenu("?");
    mnuBar.add(menu);

    JMenuItem mntmDonate = new JMenuItem(LANG.getString("frmMain.menu.Donate"));
    menu.add(mntmDonate);
    mntmDonate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            donateButton();
        }
    });

    JMenuItem mntmAbout = new JMenuItem(LANG.getString("frmMain.menu.About"));
    mntmAbout.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            FrmAbout about = new FrmAbout();
            about.setVisible(true);
        }
    });
    menu.add(mntmAbout);

    JMenuItem mntmShowLogfile = new JMenuItem(LANG.getString("frmMain.menu.ShowLogfile"));
    mntmShowLogfile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            DesktopUtil.openDir(new File(System.getProperty("user.home") + "/YouPloader"));
        }
    });
    menu.add(mntmShowLogfile);

    JMenuItem mntmUploadLogfile = new JMenuItem(LANG.getString("frmMain.menu.UploadLatestLogfile"));
    mntmUploadLogfile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            DesktopUtil.openDir(new File(System.getProperty("user.home") + "/YouPloader"));
        }
    });
    menu.add(mntmUploadLogfile);

    chckbxmntmCheckForUpdates = new JCheckBoxMenuItem(LANG.getString("frmMain.menu.CheckforUpdates"));
    menu.add(chckbxmntmCheckForUpdates);
    if (Main.s.setting.get("notify_updates").equals("1")) {
        chckbxmntmCheckForUpdates.setSelected(true);
    }
    chckbxmntmCheckForUpdates.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            toggleUpdateNotifier();
        }
    });
    setJMenuBar(mnuBar);
}

From source file:edu.harvard.mcz.imagecapture.MainFrame.java

/**
 * This method initializes jMenuItem2   
 *    /*from w  w w.j  a va2  s .  c o  m*/
 * @return javax.swing.JMenuItem   
 */
private JMenuItem getJMenuItemPaste() {
    if (jMenuItemPaste == null) {
        jMenuItemPaste = new JMenuItem(new DefaultEditorKit.PasteAction());
        jMenuItemPaste.setText("Paste");
        jMenuItemPaste.setMnemonic(KeyEvent.VK_P);
        jMenuItemPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
        jMenuItemPaste.setEnabled(true);
    }
    return jMenuItemPaste;
}

From source file:com.diversityarrays.kdxplore.trialmgr.trait.TraitExplorerPanel.java

public TraitExplorerPanel(MessagePrinter mp, OfflineData od, DALClientProvider clientProvider,
        // KdxUploadHandler uploadHandler,
        BackgroundRunner backgroundRunner, ImageIcon addBarcodeIcon,
        Transformer<Trial, Boolean> checkIfEditorActive) {
    super(new BorderLayout());

    this.backgroundRunner = backgroundRunner;
    this.clientProvider = clientProvider;
    // this.uploadHandler = uploadHandler;
    this.messagePrinter = mp;
    this.offlineData = od;
    this.checkIfEditorActive = checkIfEditorActive;

    offlineData.addOfflineDataChangeListener(offlineDataListener);

    editingLocked.setIcon(KDClientUtils.getIcon(ImageId.LOCKED));
    editingLocked.addActionListener(new ActionListener() {
        @Override//from www  . j  av a  2  s .c  om
        public void actionPerformed(ActionEvent e) {
            changeEditable(editingLocked.isSelected(), DONT_OVERRIDE);
        }
    });

    changeManager.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            updateUndoRedoActions();
        }
    });

    KDClientUtils.initAction(ImageId.TRASH_24, deleteTraitsAction, "Remove Trait");
    deleteTraitsAction.setEnabled(false);

    KDClientUtils.initAction(ImageId.REFRESH_24, refreshAction, "Refresh Data");

    KDClientUtils.initAction(ImageId.PLUS_BLUE_24, addNewTraitAction, "Add Trait");

    KDClientUtils.initAction(ImageId.UPLOAD_24, uploadTraitsAction, "Upload Traits");

    KDClientUtils.initAction(ImageId.ADD_TRIALS_24, importTraitsAction, "Import Traits");

    KDClientUtils.initAction(ImageId.EXPORT_24, exportTraitsAction, "Export Traits");

    try {
        Class.forName("com.diversityarrays.kdxplore.upload.TraitUploadTask");
    } catch (ClassNotFoundException e1) {
        uploadTraitsAction.setEnabled(false);
        if (RunMode.getRunMode().isDeveloper()) {
            new Toast((JComponent) null,
                    "<HTML>Developer Warning<BR>" + "Trait Upload currently unavailable<BR>", 4000)
                            .showAsError();
        }
    }

    traitPropertiesTable
            .setTransferHandler(TableTransferHandler.initialiseForCopySelectAll(traitPropertiesTable, true));
    traitPropertiesTableModel.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            if (traitPropertiesTableModel.getRowCount() > 0) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        GuiUtil.initialiseTableColumnWidths(traitPropertiesTable);
                    }
                });
                traitPropertiesTableModel.removeTableModelListener(this);
            }
        }
    });

    traitTableModel.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            showCorrectCard();
        }
    });

    TrialManagerPreferences preferences = TrialManagerPreferences.getInstance();
    preferences.addChangeListener(TrialManagerPreferences.BAD_FOR_CALC, badForCalcColorChangeListener);
    badForCalc.setForeground(preferences.getBadForCalcColor());
    badForCalc.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (SwingUtilities.isLeftMouseButton(e)) {
                KdxPreference<Color> pref = TrialManagerPreferences.BAD_FOR_CALC;
                String title = pref.getName();
                KdxplorePreferenceEditor.startEditorDialog(TraitExplorerPanel.this, title, pref);
            }
        }
    });

    traitsTable.setAutoCreateRowSorter(true);
    int index = traitTableModel.getTraitNameColumnIndex();
    if (index >= 0) {
        traitsTable.getColumnModel().getColumn(index).setCellRenderer(traitNameCellRenderer);
    }

    traitsTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (SwingUtilities.isLeftMouseButton(e) && 2 == e.getClickCount()) {
                e.consume();

                int vrow = traitsTable.rowAtPoint(e.getPoint());
                if (vrow >= 0) {
                    int mrow = traitsTable.convertRowIndexToModel(vrow);
                    if (mrow >= 0) {
                        Trait trait = traitTableModel.getTraitAtRow(mrow);
                        Integer selectViewRow = null;
                        if (!traitTrialsTableModel.isSelectedTrait(trait)) {
                            selectViewRow = vrow;
                        }
                        if (traitsEditable) {
                            startEditingTraitInternal(trait, selectViewRow, null);
                        } else {
                            warnEditingLocked();
                        }
                    }
                }
            }
        }
    });

    traitsTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    traitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {

                List<Trait> selectedTraits = getSelectedTraits();
                traitTrialsTableModel.setSelectedTraits(selectedTraits);

                if (selectedTraits.size() == 1) {
                    Trait trait = null;
                    int vrow = traitsTable.getSelectedRow();
                    if (vrow >= 0) {
                        int mrow = traitsTable.convertRowIndexToModel(vrow);
                        if (mrow >= 0) {
                            trait = traitTableModel.getEntityAt(mrow);
                        }
                    }
                    showTraitDetails(trait);
                }

                deleteTraitsAction.setEnabled(selectedTraits.size() > 0);

                showCorrectCard();
            }
        }
    });

    TraitTableModel.initValidationExpressionRenderer(traitsTable);
    if (RunMode.getRunMode().isDeveloper()) {
        TraitTableModel.initTableForRawExpression(traitsTable);
    }
    cardPanel.add(noTraitsComponent, CARD_NO_TRAITS);
    cardPanel.add(selectTraitComponent, CARD_SELECT_TO_EDIT);
    cardPanel.add(new JScrollPane(traitPropertiesTable), CARD_TRAIT_EDITOR);

    JButton undoButton = initAction(undoAction, ImageId.UNDO_24, "Undo",
            KeyStroke.getKeyStroke('Z', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    JButton redoButton = initAction(redoAction, ImageId.REDO_24, "Redo",
            KeyStroke.getKeyStroke('Y', Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    Box undoRedoButtons = Box.createHorizontalBox();
    undoRedoButtons.add(undoButton);
    undoRedoButtons.add(redoButton);

    JPanel detailsPanel = new JPanel(new BorderLayout());
    detailsPanel.add(GuiUtil.createLabelSeparator("Details", undoRedoButtons), BorderLayout.NORTH);
    detailsPanel.add(cardPanel, BorderLayout.CENTER);
    detailsPanel.add(legendPanel, BorderLayout.SOUTH);

    PromptScrollPane scrollPane = new PromptScrollPane(traitsTable,
            "Drag/Drop Traits CSV file or use 'Import Traits'");

    TableTransferHandler tth = TableTransferHandler.initialiseForCopySelectAll(traitsTable, true);
    traitsTable.setTransferHandler(new ChainingTransferHandler(flth, tth));

    scrollPane.setTransferHandler(flth);

    if (addBarcodeIcon == null) {
        barcodesMenuAction.putValue(Action.NAME, "Barcodes...");
    } else {
        barcodesMenuAction.putValue(Action.SMALL_ICON, addBarcodeIcon);
    }

    italicsForProtectedCheckbox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            traitNameCellRenderer.setUseItalicsForProtected(italicsForProtectedCheckbox.isSelected());
            traitsTable.repaint();
        }
    });

    Box leftTopControls = Box.createHorizontalBox();
    leftTopControls.add(importTraitsButton);
    leftTopControls.add(barcodesMenuButton);
    leftTopControls.add(new JButton(addNewTraitAction));
    leftTopControls.add(new JButton(uploadTraitsAction));
    leftTopControls.add(new JButton(exportTraitsAction));

    leftTopControls.add(Box.createHorizontalGlue());

    leftTopControls.add(editingLocked);
    leftTopControls.add(fixTraitLevelsButton);
    leftTopControls.add(refreshButton);
    leftTopControls.add(Box.createHorizontalStrut(8));
    leftTopControls.add(new JButton(deleteTraitsAction));
    // leftTopControls.add(Box.createHorizontalStrut(4));

    Box explanations = Box.createHorizontalBox();
    explanations.add(italicsForProtectedCheckbox);
    explanations.add(badForCalc);
    explanations.add(Box.createHorizontalGlue());

    fixTraitLevelsButton.setToolTipText("Fix Traits with " + TraitLevel.UNDECIDABLE.visible + " 'Level'");
    fixTraitLevelsButton.setVisible(false);

    JPanel leftTop = new JPanel(new BorderLayout());
    leftTop.add(leftTopControls, BorderLayout.NORTH);
    leftTop.add(scrollPane, BorderLayout.CENTER);
    leftTop.add(explanations, BorderLayout.SOUTH);

    JPanel leftBot = new JPanel(new BorderLayout());
    leftBot.add(GuiUtil.createLabelSeparator("Used by Trials"), BorderLayout.NORTH);
    leftBot.add(new PromptScrollPane(traitTrialsTable, "Any Trials using selected Traits appear here"));

    JSplitPane leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, leftTop, leftBot);
    leftSplit.setResizeWeight(0.5);

    splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftSplit, detailsPanel);
    splitPane.setOneTouchExpandable(true);
    splitPane.setResizeWeight(0.5);

    add(splitPane, BorderLayout.CENTER);
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java

private void myInit() {
    super.dialogInit();
    setTitle(title);//from   w w w. j  a va  2s  . c o m

    double[][] size = { { border, TableLayoutConstants.PREFERRED, border }, // Columns
            { border, TableLayoutConstants.PREFERRED, border } }; // Rows
    setLayout(new TableLayout(size));

    JButton[] commandButtons = new JButton[buttons.length];
    ArrayList<JComponent> buttonArr = new ArrayList<JComponent>();
    for (int i = 0; i < buttons.length; i++) {
        JButton button = new JButton(buttons[i]);
        final int fi = i;
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                returnValue = fi;
                dispose();
            }
        });
        commandButtons[i] = button;
        buttonArr.add(button);
    }
    // final JScrollPane sp = new JScrollPane(mainView);
    // SwingUtilities.invokeLater(new Runnable() {
    // public void run() {
    // sp.getVerticalScrollBar().setValue(0);
    // }});
    add(TableLayout.getSplitVertical(mainView,
            TableLayout.getMultiSplit(buttonArr, TableLayoutConstants.PREFERRED, 5, 0, 5, 3),
            TableLayoutConstants.FILL, TableLayoutConstants.PREFERRED), "1,1");
    validate();

    setResizable(false);
    // setSize(getPreferredSize());
    setModal(true);
    getRootPane().setDefaultButton(commandButtons[0]);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    final String ESC_ACTION_KEY = "ESC_ACTION_KEY";
    getRootPane().getActionMap().put(ESC_ACTION_KEY, new AbstractAction() {
        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent e) {
            setVisible(false);
            dispose();
        }
    });

    getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), ESC_ACTION_KEY);
    pack();
}

From source file:it.unibo.alchemist.boundary.monitors.Generic2DDisplay.java

private void bindKey(final int key, final Runnable fun) {
    final Object binder = "Key: " + key;
    getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(key, 0), binder);
    getActionMap().put(binder, new AbstractAction() {
        private static final long serialVersionUID = 7927420406960259675L;

        @Override//  w w  w .  j a v  a2  s .  c o  m
        public void actionPerformed(final ActionEvent e) {
            fun.run();
        }
    });
}

From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryBldrPane.java

/**
 * create the query builder UI.//w  w  w .  j  a v a  2 s.  co  m
 */
protected void createUI() {
    removeAll();

    JMenuItem saveItem = new JMenuItem(UIRegistry.getResourceString("QB_SAVE"));
    Action saveActionListener = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            if (saveQuery(false)) {
                try {
                    String selId = null;
                    if (selectedQFP != null && selectedQFP.getQueryField() != null) {
                        selId = selectedQFP.getQueryField().getStringId();
                    }
                    final String selectedFldId = selId;
                    setupUI(true);
                    SwingUtilities.invokeLater(new Runnable() {

                        /* (non-Javadoc)
                         * @see java.lang.Runnable#run()
                         */
                        @Override
                        public void run() {
                            if (selectedFldId != null) {
                                for (QueryFieldPanel qfp : queryFieldItems) {
                                    if (qfp.getQueryField() != null
                                            && selectedFldId.equals(qfp.getQueryField().getStringId())) {
                                        selectQFP(qfp);
                                        return;
                                    }
                                }
                                selectQFP(queryFieldItems.get(0));
                            }
                        }

                    });
                } catch (Exception ex) {

                }
                setSaveBtnEnabled(false);
            }
        }
    };
    saveItem.addActionListener(saveActionListener);

    JMenuItem saveAsItem = new JMenuItem(UIRegistry.getResourceString("QB_SAVE_AS"));
    Action saveAsActionListener = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            if (saveQuery(true)) {
                setSaveBtnEnabled(false);
            }
        }
    };
    saveAsItem.addActionListener(saveAsActionListener);
    JComponent[] itemSample = { saveItem, saveAsItem };
    saveBtn = new DropDownButton(UIRegistry.getResourceString("QB_SAVE"), null, 1,
            java.util.Arrays.asList(itemSample));
    saveBtn.addActionListener(saveActionListener);
    String ACTION_KEY = "SAVE";
    KeyStroke ctrlS = KeyStroke.getKeyStroke(KeyEvent.VK_S,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    InputMap inputMap = saveBtn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(ctrlS, ACTION_KEY);
    ActionMap actionMap = saveBtn.getActionMap();
    actionMap.put(ACTION_KEY, saveActionListener);
    ACTION_KEY = "SAVE_AS";
    KeyStroke ctrlA = KeyStroke.getKeyStroke(KeyEvent.VK_A,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    inputMap.put(ctrlA, ACTION_KEY);
    actionMap.put(ACTION_KEY, saveAsActionListener);
    saveBtn.setActionMap(actionMap);

    UIHelper.setControlSize(saveBtn);
    //saveBtn.setOverrideBorder(true, BasicBorders.getButtonBorder());

    listBoxPanel = new JPanel(new HorzLayoutManager(2, 2));

    Vector<TableQRI> list = new Vector<TableQRI>();
    for (int k = 0; k < tableTree.getKids(); k++) {
        list.add(tableTree.getKid(k).getTableQRI());
    }

    Collections.sort(list);
    DefaultListModel model = new DefaultListModel();
    for (TableQRI qri : list) {
        model.addElement(qri);
    }

    tableList = new JList(model);
    QryListRenderer qr = new QryListRenderer(IconManager.IconSize.Std16);
    qr.setDisplayKidIndicator(false);
    tableList.setCellRenderer(qr);

    JScrollPane spt = new JScrollPane(tableList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    Dimension pSize = spt.getPreferredSize();
    pSize.height = 200;
    spt.setPreferredSize(pSize);

    JPanel topPanel = new JPanel(new BorderLayout());

    scrollPane = new JScrollPane(listBoxPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

    tableList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                int inx = tableList.getSelectedIndex();
                if (inx > -1) {
                    fillNextList(tableList);
                } else {
                    listBoxPanel.removeAll();
                }
            }
        }
    });

    addBtn = new JButton(IconManager.getImage("PlusSign", IconManager.IconSize.Std16));
    addBtn.setEnabled(false);
    addBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            BaseQRI qri = (BaseQRI) listBoxList.get(currentInx).getSelectedValue();
            if (qri.isInUse) {
                return;
            }

            try {
                FieldQRI fieldQRI = buildFieldQRI(qri);
                if (fieldQRI == null) {
                    throw new Exception("null FieldQRI");
                }
                SpQueryField qf = new SpQueryField();
                qf.initialize();
                qf.setFieldName(fieldQRI.getFieldName());
                qf.setStringId(fieldQRI.getStringId());
                query.addReference(qf, "fields");

                if (!isExportMapping) {
                    addQueryFieldItem(fieldQRI, qf, false);
                } else {
                    addNewMapping(fieldQRI, qf, null, false);
                }
            } catch (Exception ex) {
                log.error(ex);
                UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(QueryBldrPane.class, ex);
                return;
            }
        }
    });

    contextPanel = new JPanel(new BorderLayout());
    contextPanel.add(createLabel("Search Context", SwingConstants.CENTER), BorderLayout.NORTH); // I18N
    contextPanel.add(spt, BorderLayout.CENTER);
    contextPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));

    JPanel schemaPanel = new JPanel(new BorderLayout());
    schemaPanel.add(scrollPane, BorderLayout.CENTER);

    topPanel.add(contextPanel, BorderLayout.WEST);
    topPanel.add(schemaPanel, BorderLayout.CENTER);
    add(topPanel, BorderLayout.NORTH);

    queryFieldsPanel = new JPanel();
    queryFieldsPanel.setLayout(new NavBoxLayoutManager(0, 2));
    queryFieldsScroll = new JScrollPane(queryFieldsPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    queryFieldsScroll.setBorder(null);
    add(queryFieldsScroll);

    //if (!isExportMapping)
    //{
    final JPanel mover = buildMoverPanel(false);
    add(mover, BorderLayout.EAST);
    // }

    String searchLbl = schemaMapping == null ? getResourceString("QB_SEARCH")
            : getResourceString("QB_EXPORT_PREVIEW");
    searchBtn = createButton(searchLbl);
    searchBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            //               int m = ae.getModifiers();
            //               boolean ors = (m & ActionEvent.ALT_MASK) > 0 && (m & ActionEvent.CTRL_MASK) > 0 && (m & ActionEvent.SHIFT_MASK) > 0;
            //               if (ors)
            //               {
            //                  System.out.println("Disjunctional conjoinment desire gesture detected");
            //               }
            //               doSearch(ors);
            doSearch(false);
        }
    });
    distinctChk = createCheckBox(UIRegistry.getResourceString("QB_DISTINCT"));
    distinctChk.setVisible(schemaMapping == null);
    if (schemaMapping == null) {
        distinctChk.setSelected(false);
        distinctChk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                new SwingWorker() {

                    /* (non-Javadoc)
                     * @see edu.ku.brc.helpers.SwingWorker#construct()
                     */
                    @Override
                    public Object construct() {
                        if (distinctChk.isSelected()) {
                            UsageTracker.incrUsageCount("QB.DistinctOn");
                        } else {
                            UsageTracker.incrUsageCount("QB.DistinctOff");
                        }
                        if ((isTreeLevelSelected() || isAggFieldSelected()) && countOnly
                                && distinctChk.isSelected()) {
                            countOnlyChk.setSelected(false);
                            countOnly = false;
                        }
                        query.setCountOnly(countOnly);
                        query.setSelectDistinct(distinctChk.isSelected());
                        setSaveBtnEnabled(thereAreItems());
                        return null;
                    }
                }.start();
            }
        });
    }
    countOnlyChk = createCheckBox(UIRegistry.getResourceString("QB_COUNT_ONLY"));
    countOnlyChk.setSelected(false);
    countOnlyChk.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            new SwingWorker() {

                /* (non-Javadoc)
                 * @see edu.ku.brc.helpers.SwingWorker#construct()
                 */
                @Override
                public Object construct() {
                    //Don't allow change while query is running.
                    if (runningResults.get() == null) {
                        countOnly = !countOnly;
                        if (countOnly) {
                            UsageTracker.incrUsageCount("QB.CountOnlyOn");
                        } else {
                            UsageTracker.incrUsageCount("QB.CountOnlyOff");
                        }
                        if ((isTreeLevelSelected() || isAggFieldSelected()) && countOnly
                                && (distinctChk.isSelected() || searchSynonymyChk.isSelected())) {
                            distinctChk.setSelected(false);
                            searchSynonymyChk.setSelected(false);
                        }
                    } else {
                        //This might be awkward and/or klunky...
                        countOnlyChk.setSelected(countOnly);
                    }
                    query.setCountOnly(countOnly);
                    query.setSelectDistinct(distinctChk.isSelected());
                    setSaveBtnEnabled(thereAreItems());
                    return null;
                }
            }.start();
        }
    });

    searchSynonymyChk = createCheckBox(UIRegistry.getResourceString("QB_SRCH_SYNONYMS"));
    searchSynonymyChk.setSelected(searchSynonymy);
    searchSynonymyChk.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            new SwingWorker() {

                /* (non-Javadoc)
                 * @see edu.ku.brc.helpers.SwingWorker#construct()
                 */
                @Override
                public Object construct() {
                    searchSynonymy = !searchSynonymy;
                    if (!searchSynonymy) {
                        UsageTracker.incrUsageCount("QB.SearchSynonymyOff");
                    } else {
                        UsageTracker.incrUsageCount("QB.SearchSynonymyOn");
                    }
                    if (isTreeLevelSelected() && countOnly && searchSynonymyChk.isSelected()) {
                        countOnlyChk.setSelected(false);
                        countOnly = false;
                    }
                    query.setSearchSynonymy(searchSynonymy);
                    setSaveBtnEnabled(thereAreItems());
                    return null;
                }
            }.start();
        }
    });

    smushedChk = createCheckBox(UIRegistry.getResourceString("QB_SMUSH_RESULTS"));
    smushedChk.setVisible(isSmushableContext());
    if (isSmushableContext()) {
        smushedChk.setSelected(smushed);
        smushedChk.setToolTipText(
                String.format(UIRegistry.getResourceString("QB_SMUSH_RESULTS_HINT"), getCatalogNumberTitle()));
        smushedChk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                new SwingWorker() {

                    /*
                     * (non-Javadoc)
                     * 
                     * @see edu.ku.brc.helpers.SwingWorker#construct()
                     */
                    @Override
                    public Object construct() {
                        smushed = !smushed;
                        if (!smushed) {
                            UsageTracker.incrUsageCount("QB.SmushedOff");
                        } else {
                            UsageTracker.incrUsageCount("QB.SmushedOn");
                        }
                        query.setSmushed(smushed);
                        setSaveBtnEnabled(thereAreItems());
                        return null;
                    }
                }.start();
            }
        });
    }

    PanelBuilder outer = new PanelBuilder(
            new FormLayout("p, 2dlu, p, 2dlu, p, 2dlu, p, 2dlu, p, 6dlu, p", "p"));

    CellConstraints cc = new CellConstraints();
    outer.add(smushedChk, cc.xy(1, 1));
    outer.add(searchSynonymyChk, cc.xy(3, 1));
    outer.add(distinctChk, cc.xy(5, 1));
    outer.add(countOnlyChk, cc.xy(7, 1));
    outer.add(searchBtn, cc.xy(9, 1));
    outer.add(saveBtn, cc.xy(11, 1));

    JPanel bottom = new JPanel(new BorderLayout());
    bottom.add(outer.getPanel(), BorderLayout.EAST);

    JButton helpBtn = UIHelper.createHelpIconButton(getHelpBtnContext());
    bottom.add(helpBtn, BorderLayout.WEST);
    add(bottom, BorderLayout.SOUTH);

    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}

From source file:org.jas.gui.MainWindow.java

private void registerKeyStrokeAction() {
    KeyStroke ctrlo = KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK);
    KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    inputMap = getOpenButton().getInputMap(JButton.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(ctrlo, CTRL_O);/*w ww.  j  a  v  a  2 s.co m*/
    inputMap.put(enter, ENTER);
    getOpenButton().getActionMap().put(CTRL_O, new ClickAction(getOpenButton()));
    getOpenButton().getActionMap().put(ENTER, new ClickAction(getOpenButton()));
}