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:org.alex73.skarynka.scan.ui.scan.ScanDialogController.java

void addAction(int keyCode, Action action) {
    InputMap im = dialog.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    im.put(KeyStroke.getKeyStroke(keyCode, 0), action.getValue(Action.NAME));
    dialog.getRootPane().getActionMap().put(action.getValue(Action.NAME), action);
}

From source file:org.apache.cassandra.contrib.circuit.CircuitFrame.java

public CircuitFrame(String hostname, int port) {
    super(appTitle);
    setSize(defaultSize);//from  w  w  w . ja v a2  s . co  m
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // The menu bar w/ items.
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    menuBar.add(fileMenu);

    quitMI = new JMenuItem("Quit");
    quitMI.setMnemonic(KeyEvent.VK_Q);
    quitMI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK));
    quitMI.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    fileMenu.add(quitMI);

    JMenu toolsMenu = new JMenu("Tools");
    toolsMenu.setMnemonic(KeyEvent.VK_T);
    menuBar.add(toolsMenu);

    verifyMI = new JMenuItem("Verify Ring");
    verifyMI.addActionListener(this);
    toolsMenu.add(verifyMI);

    JMenu helpMenu = new JMenu("Help");
    helpMenu.setMnemonic(KeyEvent.VK_H);
    menuBar.add(helpMenu);

    aboutMI = new JMenuItem("About");
    aboutMI.setMnemonic(KeyEvent.VK_A);
    aboutMI.addActionListener(this);
    helpMenu.add(aboutMI);

    // FIXME: a progress dialog should be up while instantiating RingPanel
    ringModel = new RingModel(hostname, port);
    ringPanel = new RingPanel(ringModel);

    statusOutput = new JTextArea();
    statusOutput.setEditable(false);
    Component logPanel = new JScrollPane(statusOutput);

    JSplitPane contentPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, ringPanel, logPanel);
    setContentPane(contentPane);

    // Order matters here...
    ringPanel.setPreferredSize(getSize());
    setVisible(true);
    contentPane.setDividerLocation(0.8);
}

From source file:org.apache.cayenne.modeler.action.OpenProjectAction.java

public KeyStroke getAcceleratorKey() {
    return KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
}

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Activates itself as a viewer by configuring Size, and location of itself,
 * and configures the default Tabbed Pane elements with the correct layout,
 * table columns, and sets itself viewable.
 *//*from www .j a v a2  s. c o m*/
public void activateViewer() {
    LoggerRepository repo = LogManager.getLoggerRepository();
    if (repo instanceof LoggerRepositoryEx) {
        this.pluginRegistry = ((LoggerRepositoryEx) repo).getPluginRegistry();
    }
    initGUI();

    initPrefModelListeners();

    /**
     * We add a simple appender to the MessageCenter logger
     * so that each message is displayed in the Status bar
     */
    MessageCenter.getInstance().getLogger().addAppender(new AppenderSkeleton() {
        protected void append(LoggingEvent event) {
            getStatusBar().setMessage(event.getMessage().toString());
        }

        public void close() {
        }

        public boolean requiresLayout() {
            return false;
        }
    });

    initSocketConnectionListener();

    if (pluginRegistry.getPlugins(Receiver.class).size() == 0) {
        noReceiversDefined = true;
    }

    getFilterableColumns().add(ChainsawConstants.LEVEL_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.LOGGER_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.THREAD_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.NDC_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.PROPERTIES_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.CLASS_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.METHOD_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.FILE_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.NONE_COL_NAME);

    JPanel panePanel = new JPanel();
    panePanel.setLayout(new BorderLayout(2, 2));

    getContentPane().setLayout(new BorderLayout());

    getTabbedPane().addChangeListener(getToolBarAndMenus());
    getTabbedPane().addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            LogPanel thisLogPanel = getCurrentLogPanel();
            if (thisLogPanel != null) {
                thisLogPanel.updateStatusBar();
            }
        }
    });

    KeyStroke ksRight = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    KeyStroke ksLeft = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    KeyStroke ksGotoLine = KeyStroke.getKeyStroke(KeyEvent.VK_G,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksRight, "MoveRight");
    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksLeft, "MoveLeft");
    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksGotoLine, "GotoLine");

    Action moveRight = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int temp = getTabbedPane().getSelectedIndex();
            ++temp;

            if (temp != getTabbedPane().getTabCount()) {
                getTabbedPane().setSelectedTab(temp);
            }
        }
    };

    Action moveLeft = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int temp = getTabbedPane().getSelectedIndex();
            --temp;

            if (temp > -1) {
                getTabbedPane().setSelectedTab(temp);
            }
        }
    };

    Action gotoLine = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            String inputLine = JOptionPane.showInputDialog(LogUI.this, "Enter the line number to go:",
                    "Goto Line", -1);
            try {
                int lineNumber = Integer.parseInt(inputLine);
                int row = getCurrentLogPanel().setSelectedEvent(lineNumber);
                if (row == -1) {
                    JOptionPane.showMessageDialog(LogUI.this, "You have entered an invalid line number",
                            "Error", 0);
                }
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(LogUI.this, "You have entered an invalid line number", "Error",
                        0);
            }
        }
    };

    getTabbedPane().getActionMap().put("MoveRight", moveRight);
    getTabbedPane().getActionMap().put("MoveLeft", moveLeft);
    getTabbedPane().getActionMap().put("GotoLine", gotoLine);

    /**
         * We listen for double clicks, and auto-undock currently selected Tab if
         * the mouse event location matches the currently selected tab
         */
    getTabbedPane().addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);

            if ((e.getClickCount() > 1) && ((e.getModifiers() & InputEvent.BUTTON1_MASK) > 0)) {
                int tabIndex = getTabbedPane().getSelectedIndex();

                if ((tabIndex != -1) && (tabIndex == getTabbedPane().getSelectedIndex())) {
                    LogPanel logPanel = getCurrentLogPanel();

                    if (logPanel != null) {
                        logPanel.undock();
                    }
                }
            }
        }
    });

    panePanel.add(getTabbedPane());
    addWelcomePanel();

    getContentPane().add(toolbar, BorderLayout.NORTH);
    getContentPane().add(statusBar, BorderLayout.SOUTH);

    mainReceiverSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panePanel, receiversPanel);
    dividerSize = mainReceiverSplitPane.getDividerSize();
    mainReceiverSplitPane.setDividerLocation(-1);

    getContentPane().add(mainReceiverSplitPane, BorderLayout.CENTER);

    /**
     * We need to make sure that all the internal GUI components have been added to the
     * JFrame so that any plugns that get activated during initPlugins(...) method
     * have access to inject menus  
     */
    initPlugins(pluginRegistry);

    mainReceiverSplitPane.setResizeWeight(1.0);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent event) {
            exit();
        }
    });
    preferencesFrame.setTitle("'Application-wide Preferences");
    preferencesFrame.setIconImage(((ImageIcon) ChainsawIcons.ICON_PREFERENCES).getImage());
    preferencesFrame.getContentPane().add(applicationPreferenceModelPanel);

    preferencesFrame.setSize(750, 520);

    Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
    preferencesFrame.setLocation(new Point((screenDimension.width / 2) - (preferencesFrame.getSize().width / 2),
            (screenDimension.height / 2) - (preferencesFrame.getSize().height / 2)));

    pack();

    final JPopupMenu tabPopup = new JPopupMenu();
    final Action hideCurrentTabAction = new AbstractAction("Hide") {
        public void actionPerformed(ActionEvent e) {
            Component selectedComp = getTabbedPane().getSelectedComponent();
            if (selectedComp instanceof LogPanel) {
                displayPanel(getCurrentLogPanel().getIdentifier(), false);
                tbms.stateChange();
            } else {
                getTabbedPane().remove(selectedComp);
            }
        }
    };

    final Action hideOtherTabsAction = new AbstractAction("Hide Others") {
        public void actionPerformed(ActionEvent e) {
            Component selectedComp = getTabbedPane().getSelectedComponent();
            String currentName;
            if (selectedComp instanceof LogPanel) {
                currentName = getCurrentLogPanel().getIdentifier();
            } else if (selectedComp instanceof WelcomePanel) {
                currentName = ChainsawTabbedPane.WELCOME_TAB;
            } else {
                currentName = ChainsawTabbedPane.ZEROCONF;
            }

            int count = getTabbedPane().getTabCount();
            int index = 0;

            for (int i = 0; i < count; i++) {
                String name = getTabbedPane().getTitleAt(index);

                if (getPanelMap().keySet().contains(name) && !name.equals(currentName)) {
                    displayPanel(name, false);
                    tbms.stateChange();
                } else {
                    index++;
                }
            }
        }
    };

    Action showHiddenTabsAction = new AbstractAction("Show All Hidden") {
        public void actionPerformed(ActionEvent e) {
            for (Iterator iter = getPanels().entrySet().iterator(); iter.hasNext();) {
                Map.Entry entry = (Map.Entry) iter.next();
                Boolean docked = (Boolean) entry.getValue();
                if (docked.booleanValue()) {
                    String identifier = (String) entry.getKey();
                    int count = getTabbedPane().getTabCount();
                    boolean found = false;

                    for (int i = 0; i < count; i++) {
                        String name = getTabbedPane().getTitleAt(i);

                        if (name.equals(identifier)) {
                            found = true;

                            break;
                        }
                    }

                    if (!found) {
                        displayPanel(identifier, true);
                        tbms.stateChange();
                    }
                }
            }
        }
    };

    tabPopup.add(hideCurrentTabAction);
    tabPopup.add(hideOtherTabsAction);
    tabPopup.addSeparator();
    tabPopup.add(showHiddenTabsAction);

    final PopupListener tabPopupListener = new PopupListener(tabPopup);
    getTabbedPane().addMouseListener(tabPopupListener);

    this.handler.addPropertyChangeListener("dataRate", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            double dataRate = ((Double) evt.getNewValue()).doubleValue();
            statusBar.setDataRate(dataRate);
        }
    });

    getSettingsManager().addSettingsListener(this);
    getSettingsManager().addSettingsListener(MRUFileListPreferenceSaver.getInstance());
    getSettingsManager().addSettingsListener(receiversPanel);
    try {
        //if an uncaught exception is thrown, allow the UI to continue to load
        getSettingsManager().loadSettings();
    } catch (Exception e) {
        e.printStackTrace();
    }
    //app preferences have already been loaded (and configuration url possibly set to blank if being overridden)
    //but we need a listener so the settings will be saved on exit (added after loadsettings was called)
    getSettingsManager().addSettingsListener(new ApplicationPreferenceModelSaver(applicationPreferenceModel));

    setVisible(true);

    if (applicationPreferenceModel.isReceivers()) {
        showReceiverPanel();
    } else {
        hideReceiverPanel();
    }

    removeSplash();

    synchronized (initializationLock) {
        isGUIFullyInitialized = true;
        initializationLock.notifyAll();
    }

    if (noReceiversDefined && applicationPreferenceModel.isShowNoReceiverWarning()) {
        SwingHelper.invokeOnEDT(new Runnable() {
            public void run() {
                showReceiverConfigurationPanel();
            }
        });
    }

    Container container = tutorialFrame.getContentPane();
    final JEditorPane tutorialArea = new JEditorPane();
    tutorialArea.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    tutorialArea.setEditable(false);
    container.setLayout(new BorderLayout());

    try {
        tutorialArea.setPage(ChainsawConstants.TUTORIAL_URL);
        JTextComponentFormatter.applySystemFontAndSize(tutorialArea);

        container.add(new JScrollPane(tutorialArea), BorderLayout.CENTER);
    } catch (Exception e) {
        MessageCenter.getInstance().getLogger().error("Error occurred loading the Tutorial", e);
    }

    tutorialFrame.setIconImage(new ImageIcon(ChainsawIcons.HELP).getImage());
    tutorialFrame.setSize(new Dimension(640, 480));

    final Action startTutorial = new AbstractAction("Start Tutorial",
            new ImageIcon(ChainsawIcons.ICON_RESUME_RECEIVER)) {
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(null,
                    "This will start 3 \"Generator\" receivers for use in the Tutorial.  Is that ok?",
                    "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                new Thread(new Tutorial()).start();
                putValue("TutorialStarted", Boolean.TRUE);
            } else {
                putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    };

    final Action stopTutorial = new AbstractAction("Stop Tutorial",
            new ImageIcon(ChainsawIcons.ICON_STOP_RECEIVER)) {
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(null,
                    "This will stop all of the \"Generator\" receivers used in the Tutorial, but leave any other Receiver untouched.  Is that ok?",
                    "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                new Thread(new Runnable() {
                    public void run() {
                        LoggerRepository repo = LogManager.getLoggerRepository();
                        if (repo instanceof LoggerRepositoryEx) {
                            PluginRegistry pluginRegistry = ((LoggerRepositoryEx) repo).getPluginRegistry();
                            List list = pluginRegistry.getPlugins(Generator.class);

                            for (Iterator iter = list.iterator(); iter.hasNext();) {
                                Plugin plugin = (Plugin) iter.next();
                                pluginRegistry.stopPlugin(plugin.getName());
                            }
                        }
                    }
                }).start();
                setEnabled(false);
                startTutorial.putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    };

    stopTutorial.putValue(Action.SHORT_DESCRIPTION,
            "Removes all of the Tutorials Generator Receivers, leaving all other Receivers untouched");
    startTutorial.putValue(Action.SHORT_DESCRIPTION,
            "Begins the Tutorial, starting up some Generator Receivers so you can see Chainsaw in action");
    stopTutorial.setEnabled(false);

    final SmallToggleButton startButton = new SmallToggleButton(startTutorial);
    PropertyChangeListener pcl = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            stopTutorial.setEnabled(((Boolean) startTutorial.getValue("TutorialStarted")).equals(Boolean.TRUE));
            startButton.setSelected(stopTutorial.isEnabled());
        }
    };

    startTutorial.addPropertyChangeListener(pcl);
    stopTutorial.addPropertyChangeListener(pcl);

    pluginRegistry.addPluginListener(new PluginListener() {
        public void pluginStarted(PluginEvent e) {
        }

        public void pluginStopped(PluginEvent e) {
            List list = pluginRegistry.getPlugins(Generator.class);

            if (list.size() == 0) {
                startTutorial.putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    });

    final SmallButton stopButton = new SmallButton(stopTutorial);

    final JToolBar tutorialToolbar = new JToolBar();
    tutorialToolbar.setFloatable(false);
    tutorialToolbar.add(startButton);
    tutorialToolbar.add(stopButton);
    container.add(tutorialToolbar, BorderLayout.NORTH);
    tutorialArea.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                if (e.getDescription().equals("StartTutorial")) {
                    startTutorial.actionPerformed(null);
                } else if (e.getDescription().equals("StopTutorial")) {
                    stopTutorial.actionPerformed(null);
                } else {
                    try {
                        tutorialArea.setPage(e.getURL());
                    } catch (IOException e1) {
                        MessageCenter.getInstance().getLogger()
                                .error("Failed to change the URL for the Tutorial", e1);
                    }
                }
            }
        }
    });

    /**
     * loads the saved tab settings and if there are hidden tabs,
     * hide those tabs out of currently loaded tabs..
     */

    if (!getTabbedPane().tabSetting.isWelcome()) {
        displayPanel(ChainsawTabbedPane.WELCOME_TAB, false);
    }
    if (!getTabbedPane().tabSetting.isZeroconf()) {
        displayPanel(ChainsawTabbedPane.ZEROCONF, false);
    }
    tbms.stateChange();

}

From source file:org.apache.pdfbox.debugger.PDFDebugger.java

private JMenu createFileMenu() {
    JMenuItem openMenuItem = new JMenuItem("Open...");
    openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, SHORCUT_KEY_MASK));
    openMenuItem.addActionListener(new ActionListener() {
        @Override// w  w w .j a v  a 2  s .  c om
        public void actionPerformed(ActionEvent evt) {
            openMenuItemActionPerformed(evt);
        }
    });

    JMenu fileMenu = new JMenu("File");
    fileMenu.add(openMenuItem);
    fileMenu.setMnemonic('F');

    JMenuItem openUrlMenuItem = new JMenuItem("Open URL...");
    openUrlMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, SHORCUT_KEY_MASK));
    openUrlMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            String urlString = JOptionPane.showInputDialog("Enter an URL");
            if (urlString == null || urlString.isEmpty()) {
                return;
            }
            try {
                readPDFurl(urlString, "");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
    fileMenu.add(openUrlMenuItem);

    reopenMenuItem = new JMenuItem("Reopen");
    reopenMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, SHORCUT_KEY_MASK));
    reopenMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            try {
                if (currentFilePath.startsWith("http")) {
                    readPDFurl(currentFilePath, "");
                } else {
                    readPDFFile(currentFilePath, "");
                }
            } catch (IOException e) {
                new ErrorDialog(e).setVisible(true);
            }
        }
    });
    reopenMenuItem.setEnabled(false);
    fileMenu.add(reopenMenuItem);

    try {
        recentFiles = new RecentFiles(this.getClass(), 5);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    recentFilesMenu = new JMenu("Open Recent");
    recentFilesMenu.setEnabled(false);
    addRecentFileItems();
    fileMenu.add(recentFilesMenu);

    printMenuItem = new JMenuItem("Print");
    printMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, SHORCUT_KEY_MASK));
    printMenuItem.setEnabled(false);
    printMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            printMenuItemActionPerformed(evt);
        }
    });

    if (!IS_MAC_OS) {
        fileMenu.addSeparator();
        fileMenu.add(printMenuItem);
    }

    JMenuItem exitMenuItem = new JMenuItem("Exit");
    exitMenuItem.setAccelerator(KeyStroke.getKeyStroke("alt F4"));
    exitMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            exitMenuItemActionPerformed(evt);
        }
    });

    if (!IS_MAC_OS) {
        fileMenu.addSeparator();
        fileMenu.add(exitMenuItem);
    }

    return fileMenu;
}

From source file:org.apache.pdfbox.debugger.PDFDebugger.java

private JMenu createFindMenu() {
    findMenu = new JMenu("Find");
    findMenu.setEnabled(false);/*from w  w  w. j  ava2s .  c  o  m*/

    findMenuItem = new JMenuItem("Find...");
    findMenuItem.setActionCommand("find");
    findMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, SHORCUT_KEY_MASK));

    findNextMenuItem = new JMenuItem("Find Next");
    if (IS_MAC_OS) {
        findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, SHORCUT_KEY_MASK));
    } else {
        findNextMenuItem.setAccelerator(KeyStroke.getKeyStroke("F3"));
    }

    findPreviousMenuItem = new JMenuItem("Find Previous");
    if (IS_MAC_OS) {
        findPreviousMenuItem.setAccelerator(
                KeyStroke.getKeyStroke(KeyEvent.VK_G, SHORCUT_KEY_MASK | InputEvent.SHIFT_DOWN_MASK));
    } else {
        findPreviousMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, InputEvent.SHIFT_DOWN_MASK));
    }

    findMenu.add(findMenuItem);
    findMenu.add(findNextMenuItem);
    findMenu.add(findPreviousMenuItem);

    return findMenu;
}

From source file:org.codinjutsu.tools.jenkins.view.BuildParamDialog.java

private void registerListeners() {
    buttonOK.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            onOK();/*w w  w.  java2  s. co  m*/
        }
    });

    buttonCancel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            onCancel();
        }
    });

    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            onCancel();
        }
    });

    contentPane.registerKeyboardAction(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            onCancel();
        }
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}

From source file:org.dishevelled.brainstorm.BrainStorm.java

/**
 * Initialize components./*from  ww  w . j  av a2  s.  c  o m*/
 */
private void initComponents() {
    Font font = new Font(chooseFontName(), Font.PLAIN, fontSize);
    hiddenCursor = createHiddenCursor();
    textArea = new JTextArea() {
        /** {@inheritDoc} */
        protected void paintComponent(final Graphics graphics) {
            Graphics2D g2 = (Graphics2D) graphics;
            g2.setRenderingHint(KEY_FRACTIONALMETRICS, VALUE_FRACTIONALMETRICS_ON);
            g2.setRenderingHint(KEY_TEXT_ANTIALIASING, VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            super.paintComponent(g2);
        }
    };
    textArea.setFont(font);
    textArea.setOpaque(true);
    textArea.setCursor(hiddenCursor);
    textArea.setBackground(backgroundColor);
    textArea.setForeground(textColor);
    textArea.setRows(rows);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);

    // clear all input mappings
    InputMap inputMap = textArea.getInputMap();
    while (inputMap != null) {
        inputMap.clear();
        inputMap = inputMap.getParent();
    }
    // re-add select default input mappings
    textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "insert-break");
    textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), "insert-tab");
    textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), "delete-previous");
    int keyMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
    textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, keyMask), "delete-previous-word");

    // add new input mappings
    textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, keyMask), "increase-font-size");
    textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, keyMask), "decrease-font-size");
    textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_S, keyMask), "save");
    textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "quit");
    textArea.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_Q, keyMask), "quit");

    Action increaseFontSizeAction = new IncreaseFontSizeAction();
    Action decreaseFontSizeAction = new DecreaseFontSizeAction();
    Action saveAction = new SaveAction();
    Action quitAction = new QuitAction();

    textArea.getActionMap().put("increase-font-size", increaseFontSizeAction);
    textArea.getActionMap().put("decrease-font-size", decreaseFontSizeAction);
    textArea.getActionMap().put("save", saveAction);
    textArea.getActionMap().put("quit", quitAction);

    placeholder = Box.createGlue();
}

From source file:org.docx4all.swing.text.WordMLEditorKit.java

private void initKeyBindings(JEditorPane editor) {
    ActionMap myActionMap = new ActionMap();
    InputMap myInputMap = new InputMap();

    KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK);
    myActionMap.put(insertSoftBreakAction, new InsertSoftBreakAction(insertSoftBreakAction));
    myInputMap.put(ks, insertSoftBreakAction);

    ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    myActionMap.put(enterKeyTypedAction, new EnterKeyTypedAction(enterKeyTypedAction));
    myInputMap.put(ks, enterKeyTypedAction);

    ks = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
    myActionMap.put(deleteNextCharAction, new DeleteNextCharAction(deleteNextCharAction));
    myInputMap.put(ks, deleteNextCharAction);

    ks = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0);
    myActionMap.put(deletePrevCharAction, new DeletePrevCharAction(deletePrevCharAction));
    myInputMap.put(ks, deletePrevCharAction);

    myActionMap.setParent(editor.getActionMap());
    myInputMap.setParent(editor.getInputMap());
    editor.setActionMap(myActionMap);//from   w w w.ja va 2 s.  c  o  m
    editor.setInputMap(JComponent.WHEN_FOCUSED, myInputMap);
}

From source file:org.domainmath.gui.FileTreePanel.java

/**
 * Creates new form FileTreePanel/*from w ww.  j a  v  a2  s.  com*/
 * @param frame
 */

public FileTreePanel(MainFrame frame) {
    initComponents();
    this.frame = frame;
    fileTree.setEditable(true);
    addPopupMenuToFileTree();

    ToolTipManager.sharedInstance().registerComponent(fileTree);

    // handle right click event on File Tree.
    fileTree.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            if (e.getClickCount() == 2) {
                TreePath path = fileTree.getPathForLocation(e.getX(), e.getY());
                Rectangle pathBounds = fileTree.getUI().getPathBounds(fileTree, path);
                if (pathBounds != null && pathBounds.contains(e.getX(), e.getY())) {
                    File file = (File) fileTree.getLastSelectedPathComponent();
                    selectFile(file);
                }
            }
        }
    });

    keyDeleteItem = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
    keyRenameItem = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
    keyOpenItem = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    keyRefreshItem = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0);
}