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(String s) 

Source Link

Document

Parses a string and returns a KeyStroke.

Usage

From source file:be.ac.ua.comp.scarletnebula.gui.windows.GUI.java

private void setKeyboardAccelerators() {
    serverList.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control F"),
            "search");
    serverList.getActionMap().put("search", new AbstractAction() {
        private static final long serialVersionUID = 1L;

        @Override//  w  w w .  j a  v  a  2  s .co  m
        public void actionPerformed(final ActionEvent e) {
            showFilter();
        }
    });
}

From source file:com.ficeto.esp.EspExceptionDecoder.java

private void createAndUpload() {
    if (!PreferencesData.get("target_platform").contentEquals("esp8266")
            && !PreferencesData.get("target_platform").contentEquals("esp32")
            && !PreferencesData.get("target_platform").contentEquals("ESP31B")) {
        System.err.println();/*w  w  w  .ja  v a2  s  . c o  m*/
        editor.statusError("Not Supported on " + PreferencesData.get("target_platform"));
        return;
    }

    String tc = "esp32";
    if (PreferencesData.get("target_platform").contentEquals("esp8266")) {
        tc = "lx106";
    }

    TargetPlatform platform = BaseNoGui.getTargetPlatform();

    String gccPath = PreferencesData.get("runtime.tools.xtensa-" + tc + "-elf-gcc.path");
    if (gccPath == null) {
        gccPath = platform.getFolder() + "/tools/xtensa-" + tc + "-elf";
    }

    String addr2line;
    if (PreferencesData.get("runtime.os").contentEquals("windows"))
        addr2line = "xtensa-" + tc + "-elf-addr2line.exe";
    else
        addr2line = "xtensa-" + tc + "-elf-addr2line";

    tool = new File(gccPath + "/bin", addr2line);
    if (!tool.exists() || !tool.isFile()) {
        System.err.println();
        editor.statusError("ERROR: " + addr2line + " not found!");
        return;
    }

    elf = new File(getBuildFolderPath(editor.getSketch()), editor.getSketch().getName() + ".ino.elf");
    if (!elf.exists() || !elf.isFile()) {
        elf = new File(getBuildFolderPath(editor.getSketch()), editor.getSketch().getName() + ".cpp.elf");
        if (!elf.exists() || !elf.isFile()) {
            //lets give the user a chance to select the elf
            final JFileChooser fc = new JFileChooser();
            fc.addChoosableFileFilter(new ElfFilter());
            fc.setAcceptAllFileFilterUsed(false);
            int returnVal = fc.showDialog(editor, "Select ELF");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                elf = fc.getSelectedFile();
            } else {
                editor.statusError("ERROR: elf was not found!");
                System.err.println("Open command cancelled by user.");
                return;
            }
        }
    }

    JFrame.setDefaultLookAndFeelDecorated(true);
    frame = new JFrame("Exception Decoder");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    inputArea = new JTextArea("Paste your stack trace here", 16, 60);
    inputArea.setLineWrap(true);
    inputArea.setWrapStyleWord(true);
    inputArea.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "commit");
    inputArea.getActionMap().put("commit", new CommitAction());
    inputArea.getDocument().addDocumentListener(this);
    frame.getContentPane().add(new JScrollPane(inputArea), BorderLayout.PAGE_START);

    outputText = "";
    outputArea = new JTextPane();
    outputArea.setContentType("text/html");
    outputArea.setEditable(false);
    outputArea.setBackground(null);
    outputArea.setBorder(null);
    outputArea.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true);
    outputArea.setText(outputText);

    JScrollPane outputScrollPane = new JScrollPane(outputArea);
    outputScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    outputScrollPane.setPreferredSize(new Dimension(640, 200));
    outputScrollPane.setMinimumSize(new Dimension(10, 10));
    frame.getContentPane().add(outputScrollPane, BorderLayout.CENTER);

    frame.pack();
    frame.setVisible(true);
}

From source file:net.pandoragames.far.ui.swing.component.UndoHistory.java

/**
 * Registers the specified text component for the undo history.
 * This enables the <code>ctrl + z</code> and <code>ctrl + y</code> shortcuts.
 * @param component to be registered for undos.
 *//*from   w  ww  .ja va 2  s  .  c  o  m*/
public void registerUndoHistory(JTextComponent component) {
    // Create an undo action and add it to the text component
    undoAction = new AbstractAction("Undo") {
        public void actionPerformed(ActionEvent evt) {
            if (UndoHistory.this.canUndo()) {
                UndoHistory.this.undo();
            }
        }
    };
    undoAction.setEnabled(false);
    component.getActionMap().put(ACTION_KEY_UNDO, undoAction);

    // Create a redo action and add it to the text component
    redoAction = new AbstractAction("Redo") {
        public void actionPerformed(ActionEvent evt) {
            if (UndoHistory.this.canRedo()) {
                UndoHistory.this.redo();
            }
        }
    };
    redoAction.setEnabled(false);
    component.getActionMap().put(ACTION_KEY_REDO, redoAction);

    // Bind the actions to ctl-Z and ctl-Y
    component.getInputMap().put(KeyStroke.getKeyStroke("control Z"), ACTION_KEY_UNDO);
    undoAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control Z"));
    component.getInputMap().put(KeyStroke.getKeyStroke("control Y"), ACTION_KEY_REDO);
    redoAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control Y"));

    // registers this UndoHistory as an UndoableEditListener
    component.getDocument().addUndoableEditListener(this);
}

From source file:dmh.kuebiko.view.NoteStackFrame.java

/**
 * Perform additional setup to the frame. This is separate from the
 * initialize() method so that the GUI builder doesn't mess with it.
 *///from   w w w .java 2  s  . c  o  m
private void additionalSetup() {
    mode = Mode.SEARCH;

    setFocusTraversalPolicy(new CustomFocusTraversalPolicy(searchText, notePanel));

    // Search Text Field.
    AutoCompleteDecorator.decorate(searchText, noteMngr.getNoteTitles(), false);
    searchText.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "clear");
    searchText.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent e) {
            onSearchTextChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            onSearchTextChanged();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            onSearchTextChanged();
        }
    });
    searchText.getActionMap().put("clear", new AbstractAction() {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            searchText.setText(null);
        }
    });

    searchText.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            setModeToSearch();
            searchText.selectAll();
        }

        @Override
        public void focusLost(FocusEvent e) {
            noteTable.selectNote(searchText.getText());
        }
    });
    searchText.addActionListener(actionMngr.getAction(NewNoteAction.class));

    // Note Table.
    noteTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent event) {
            if (event.getValueIsAdjusting()) {
                return;
            }
            final Note selectedNote = noteTable.getSelectedNote();

            if (selectedNote == null) {
                setModeToSearch();
            } else {
                setModeToEdit();
                notePanel.setNote(selectedNote);
                searchText.setText(selectedNote.getTitle());
            }
        }
    });
}

From source file:net.pandoragames.far.ui.swing.component.UndoHistory.java

/**
 * Registers the specified text component for the snapshot history.
 * This enables the <code>alt + &larr;</code> and <code>ctrl + &rarr;</code> shortcuts.
 * @param component to be registered for snapshots.
 *//*  ww w . java 2s . c o  m*/
public void registerSnapshotHistory(JTextComponent component) {
    snapshots = new SnapshotHistory(component);

    // Create a previous action and add it to the text component
    previousAction = new AbstractAction("Previous") {
        public void actionPerformed(ActionEvent evt) {
            UndoHistory.this.previous();
        }
    };
    previousAction.setEnabled(false);
    component.getActionMap().put(ACTION_KEY_PREVIOUS, previousAction);

    // Create a next action and add it to the text component
    nextAction = new AbstractAction("Next") {
        public void actionPerformed(ActionEvent evt) {
            UndoHistory.this.next();
        }
    };
    nextAction.setEnabled(false);
    component.getActionMap().put(ACTION_KEY_NEXT, nextAction);

    // Bind the actions to alt-left-arrow and alt-right arrow
    previousAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("alt LEFT"));
    component.getInputMap().put(KeyStroke.getKeyStroke("alt LEFT"), ACTION_KEY_PREVIOUS);
    component.getInputMap().put(KeyStroke.getKeyStroke("alt KP_LEFT"), ACTION_KEY_PREVIOUS);
    nextAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("alt RIGHT"));
    component.getInputMap().put(KeyStroke.getKeyStroke("alt RIGHT"), ACTION_KEY_NEXT);
    component.getInputMap().put(KeyStroke.getKeyStroke("alt KP_RIGHT"), ACTION_KEY_NEXT);
}

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

@Deprecated
public static void addEnterShortcut(com.haulmont.cuba.gui.components.TextField textField,
        final Runnable runnable) {
    JTextField impl = (JTextField) DesktopComponentsHelper.unwrap(textField);

    impl.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
    impl.getActionMap().put("enter", new ValidationAwareAction() {
        @Override//from www .  ja  v a2  s  . c  om
        public void actionPerformedAfterValidation(ActionEvent e) {
            runnable.run();
        }
    });
}

From source file:com.AandR.beans.plotting.imagePlotPanel.CanvasPanel.java

/**
 *  Add action bindings/*ww w  . j a  va  2s.  c  om*/
 *
 */
private void addBindings() {

    //  Bind First Frame    
    getActionMap().put("FirstFrame", new AbstractAction("FirstFrame") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionPlotFirstFrame();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control F"), "FirstFrame");

    //  Bind Next Frame    
    getActionMap().put("NextFrame", new AbstractAction("NextFrame") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionPlotNextFrame();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control N"), "NextFrame");

    //  Bind Choose Frame    
    getActionMap().put("ChooseFrame", new AbstractAction("ChooseFrame") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionChooseFrame();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control C"), "ChooseFrame");

    //  Bind Previous Frame    
    getActionMap().put("PreviousFrame", new AbstractAction("PreviousFrame") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionPlotPreviousFrame();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control P"), "PreviousFrame");

    //  Bind Last Frame    
    getActionMap().put("LastFrame", new AbstractAction("LastFrame") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionPlotLastFrame();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control L"), "LastFrame");

    //  Bind Toggle Log Plot    
    getActionMap().put("LogPlot", new AbstractAction("LogPlot") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionToggleLogPlot();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("L"), "LogPlot");

    //  Bind SLice Plot
    getActionMap().put("SlicePlot", new AbstractAction("SlicePlot") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionSlicePlot();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control alt C"), "SlicePlot");

    //  Bind Recenter On Viewport     
    getActionMap().put("RecenterOnViewport", new AbstractAction("RecenterOnViewport") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionCenterOnViewport();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("C"), "RecenterOnViewport");

    //  Bind Flip Horizontally     
    getActionMap().put("FlipHorz", new AbstractAction("FlipHorz") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionFlipHorizontally();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control alt H"), "FlipHorz");

    //  Bind Flip Vertically     
    getActionMap().put("FlipVert", new AbstractAction("FlipVert") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionFlipVertically();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control alt V"), "FlipVert");

    //  Bind Rotate Right     
    getActionMap().put("RotateRight", new AbstractAction("RotateRight") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionRotate(90.0f);
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control alt R"), "RotateRight");

    //  Bind Rotate Left     
    getActionMap().put("RotateLeft", new AbstractAction("RotateLeft") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionRotate(-90.0f);
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control alt L"), "RotateLeft");

    //  Bind Export Viewport     
    getActionMap().put("ExportViewport", new AbstractAction("ExportViewport") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionSaveImageFile(true);
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control S"), "ExportViewport");

    //  Bind Export Original     
    getActionMap().put("ExportOriginal", new AbstractAction("ExportOriginal") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionSaveImageFile(false);
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control alt S"), "ExportOriginal");

    //  Bind Zoom Dialog     
    getActionMap().put("ZoomDialog", new AbstractAction("ZoomDialog") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionShowZoomDialog();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control Z"), "ZoomDialog");

    //  Bind export image series
    getActionMap().put("ExportSeries", new AbstractAction("ExportSeries") {

        public void actionPerformed(ActionEvent e) {
            canvasListener.actionExportSeries();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("alt S"), "ExportSeries");

    //  Bind export image to pdf
    getActionMap().put("ExportToPDF", new AbstractAction("ExportToPDF") {

        public void actionPerformed(ActionEvent e) {
            canvasListener.actionExportToPDF(false);
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control shift P"), "ExportToPDF");

    //  Bind export image to pdf
    getActionMap().put("ExportToPDF2", new AbstractAction("ExportToPDF2") {

        public void actionPerformed(ActionEvent e) {
            canvasListener.actionExportToPDF(true);
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control alt P"), "ExportToPDF2");

    //  Bind Range Dialog     
    getActionMap().put("RangeDialog", new AbstractAction("RangeDialog") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionShowRangeDialog();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control R"), "RangeDialog");

    //  Bind View Extend Dialog     
    getActionMap().put("PhysicalExtentDialog", new AbstractAction("PhysicalExtentDialog") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionShowPhysicalDialog();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control E"), "PhysicalExtentDialog");

    //  Bind Add Basic Shape Overlay     
    getActionMap().put("AddBasicShape", new AbstractAction("AddBasicShape") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionAddShapeOverlay();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control O"), "AddBasicShape");

    //  Bind Add Basic Shape Overlay     
    getActionMap().put("AddAnnulusShape", new AbstractAction("AddAnnulusShape") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionAddAnnulusOverlay();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control U"), "AddAnnulusShape");

    //  Bind Add Text Overlay     
    getActionMap().put("AddTextOverlay", new AbstractAction("AddTextOverlay") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionAddTextOverlay();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control T"), "AddTextOverlay");

    //  Bind Arrow Overlay     
    getActionMap().put("AddArrowOverlay", new AbstractAction("AddArrowOverlay") {

        public void actionPerformed(ActionEvent evt) {
            canvasListener.actionAddArrowOverlay();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control A"), "AddArrowOverlay");

    //  Bind Colormap Chooser
    getActionMap().put("ColorMapChooser", new AbstractAction("ColorMapChooser") {

        public void actionPerformed(ActionEvent e) {
            canvasListener.actionColormapChooser();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("control M"), "ColorMapChooser");

    //  Bind Refresh Action    
    getActionMap().put("ReloadFile", new AbstractAction("ReloadFile") {

        public void actionPerformed(ActionEvent e) {
            canvasListener.actionReloadFile();
        }
    });
    getInputMap().put(KeyStroke.getKeyStroke("F5"), "ReloadFile");
}

From source file:com.limegroup.gnutella.gui.GUIUtils.java

/**
 * Moves the action for the specified character from the 'ctrl' mask
 * to the 'meta' mask./*from   w w  w . j  a  v a2s  .co m*/
 */
private static void replaceAction(InputMap map, char c) {
    KeyStroke ctrl = KeyStroke.getKeyStroke("control pressed " + c);
    KeyStroke meta = KeyStroke.getKeyStroke("meta pressed " + c);
    if (ctrl == null || meta == null)
        return;
    Object action = map.get(ctrl);
    if (action != null) {
        map.remove(ctrl);
        map.put(meta, action);
    }
}

From source file:net.sf.jabref.openoffice.StyleSelectDialog.java

private void init(String inSelection) {
    this.initSelection = inSelection;

    ButtonGroup bg = new ButtonGroup();
    bg.add(useDefaultAuthoryear);/*from  ww  w.ja  v a  2s .  c o  m*/
    bg.add(useDefaultNumerical);
    bg.add(chooseDirectly);
    bg.add(setDirectory);
    if (Globals.prefs.getBoolean(JabRefPreferences.OO_USE_DEFAULT_AUTHORYEAR_STYLE)) {
        useDefaultAuthoryear.setSelected(true);
    } else if (Globals.prefs.getBoolean(JabRefPreferences.OO_USE_DEFAULT_NUMERICAL_STYLE)) {
        useDefaultNumerical.setSelected(true);
    } else {
        if (Globals.prefs.getBoolean(JabRefPreferences.OO_CHOOSE_STYLE_DIRECTLY)) {
            chooseDirectly.setSelected(true);
        } else {
            setDirectory.setSelected(true);
        }
    }

    directFile.setText(Globals.prefs.get(JabRefPreferences.OO_DIRECT_FILE));
    styleDir.setText(Globals.prefs.get(JabRefPreferences.OO_STYLE_DIRECTORY));
    directFile.setEditable(false);
    styleDir.setEditable(false);

    popup.add(edit);

    BrowseAction dfBrowse = BrowseAction.buildForFile(directFile, directFile);
    browseDirectFile.addActionListener(dfBrowse);

    BrowseAction sdBrowse = BrowseAction.buildForDir(styleDir, setDirectory);
    browseStyleDir.addActionListener(sdBrowse);

    showDefaultAuthoryearStyle.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            displayDefaultStyle(true);
        }
    });
    showDefaultNumericalStyle.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            displayDefaultStyle(false);
        }
    });
    // Add action listener to "Edit" menu item, which is supposed to open the style file in an external editor:
    edit.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            int i = table.getSelectedRow();
            if (i == -1) {
                return;
            }
            ExternalFileType type = ExternalFileTypes.getInstance().getExternalFileTypeByExt("jstyle");
            String link = tableModel.getElementAt(i).getFile().getPath();
            try {
                if (type == null) {
                    JabRefDesktop.openExternalFileUnknown(frame, new BibEntry(), new MetaData(), link,
                            new UnknownExternalFileType("jstyle"));
                } else {
                    JabRefDesktop.openExternalFileAnyFormat(new MetaData(), link, type);
                }
            } catch (IOException e) {
                LOGGER.warn("Problem open style file editor", e);
            }
        }
    });

    diag = new JDialog(frame, Localization.lang("Styles"), true);

    styles = new BasicEventList<>();
    EventList<OOBibStyle> sortedStyles = new SortedList<>(styles);

    // Create a preview panel for previewing styles:
    preview = new PreviewPanel(null, new MetaData(), "");
    // Use the test entry from the Preview settings tab in Preferences:
    preview.setEntry(prevEntry);

    tableModel = (DefaultEventTableModel<OOBibStyle>) GlazedListsSwing
            .eventTableModelWithThreadProxyList(sortedStyles, new StyleTableFormat());
    table = new JTable(tableModel);
    TableColumnModel cm = table.getColumnModel();
    cm.getColumn(0).setPreferredWidth(100);
    cm.getColumn(1).setPreferredWidth(200);
    cm.getColumn(2).setPreferredWidth(80);
    selectionModel = (DefaultEventSelectionModel<OOBibStyle>) GlazedListsSwing
            .eventSelectionModelWithThreadProxyList(sortedStyles);
    table.setSelectionModel(selectionModel);
    table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent mouseEvent) {
            if (mouseEvent.isPopupTrigger()) {
                tablePopup(mouseEvent);
            }
        }

        @Override
        public void mouseReleased(MouseEvent mouseEvent) {
            if (mouseEvent.isPopupTrigger()) {
                tablePopup(mouseEvent);
            }
        }
    });

    selectionModel.getSelected().addListEventListener(new EntrySelectionListener());

    styleDir.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent documentEvent) {
            readStyles();
            setDirectory.setSelected(true);
        }

        @Override
        public void removeUpdate(DocumentEvent documentEvent) {
            readStyles();
            setDirectory.setSelected(true);
        }

        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
            readStyles();
            setDirectory.setSelected(true);
        }
    });
    directFile.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent documentEvent) {
            chooseDirectly.setSelected(true);
        }

        @Override
        public void removeUpdate(DocumentEvent documentEvent) {
            chooseDirectly.setSelected(true);
        }

        @Override
        public void changedUpdate(DocumentEvent documentEvent) {
            chooseDirectly.setSelected(true);
        }
    });

    contentPane.setTopComponent(new JScrollPane(table));
    contentPane.setBottomComponent(preview);

    readStyles();

    DefaultFormBuilder b = new DefaultFormBuilder(
            new FormLayout("fill:pref,4dlu,fill:150dlu,4dlu,fill:pref", ""));
    b.append(useDefaultAuthoryear, 3);
    b.append(showDefaultAuthoryearStyle);
    b.nextLine();
    b.append(useDefaultNumerical, 3);
    b.append(showDefaultNumericalStyle);
    b.nextLine();
    b.append(chooseDirectly);
    b.append(directFile);
    b.append(browseDirectFile);
    b.nextLine();
    b.append(setDirectory);
    b.append(styleDir);
    b.append(browseStyleDir);
    b.nextLine();
    DefaultFormBuilder b2 = new DefaultFormBuilder(
            new FormLayout("fill:1dlu:grow", "fill:pref, fill:pref, fill:270dlu:grow"));

    b2.nextLine();
    b2.append(new JLabel("<html>"
            + Localization.lang("This is the list of available styles. Select the one you want to use.")
            + "</html>"));
    b2.nextLine();
    b2.append(contentPane);
    b.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    b2.getPanel().setBorder(BorderFactory.createEmptyBorder(15, 5, 5, 5));
    diag.add(b.getPanel(), BorderLayout.NORTH);
    diag.add(b2.getPanel(), BorderLayout.CENTER);

    AbstractAction okListener = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent event) {
            if (!useDefaultAuthoryear.isSelected() && !useDefaultNumerical.isSelected()) {
                if (chooseDirectly.isSelected()) {
                    File f = new File(directFile.getText());
                    if (!f.exists()) {
                        JOptionPane.showMessageDialog(diag,
                                Localization.lang(
                                        "You must select either a valid style file, or use a default style."),
                                Localization.lang("Style selection"), JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                } else {
                    if ((table.getRowCount() == 0) || (table.getSelectedRowCount() == 0)) {
                        JOptionPane.showMessageDialog(diag,
                                Localization.lang(
                                        "You must select either a valid style file, or use a default style."),
                                Localization.lang("Style selection"), JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                }
            }
            okPressed = true;
            storeSettings();
            diag.dispose();
        }
    };
    ok.addActionListener(okListener);

    Action cancelListener = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent event) {
            diag.dispose();
        }
    };
    cancel.addActionListener(cancelListener);

    ButtonBarBuilder bb = new ButtonBarBuilder();
    bb.addGlue();
    bb.addButton(ok);
    bb.addButton(cancel);
    bb.addGlue();
    bb.getPanel().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    diag.add(bb.getPanel(), BorderLayout.SOUTH);

    ActionMap am = bb.getPanel().getActionMap();
    InputMap im = bb.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close");
    am.put("close", cancelListener);
    im.put(KeyStroke.getKeyStroke("ENTER"), "enterOk");
    am.put("enterOk", okListener);

    diag.pack();
    diag.setLocationRelativeTo(frame);
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            contentPane.setDividerLocation(contentPane.getSize().height - 150);
        }
    });

}

From source file:com.chart.SwingChart.java

/**
 * /*from  w  ww. jav a2  s .  co  m*/
 * @param name Chart name
 * @param parent Skeleton parent
 * @param axes Configuration of axes
 * @param abcissaName Abcissa name
 */
public SwingChart(String name, final Skeleton parent, List<AxisChart> axes, String abcissaName) {
    this.skeleton = parent;
    this.axes = axes;
    this.name = name;

    this.abcissaFormat = NumberFormat.getInstance(Locale.getDefault());
    this.ordinateFormat = NumberFormat.getInstance(Locale.getDefault());

    plot = new XYPlot();
    plot.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strChartBackgroundColor)));
    plot.setDomainGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));
    plot.setRangeGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));

    abcissaAxis = new NumberAxis(abcissaName);
    ((NumberAxis) abcissaAxis).setAutoRangeIncludesZero(false);
    abcissaAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    abcissaAxis.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    abcissaAxis.setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    abcissaAxis.setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    abcissaAxis.setAutoRange(true);
    abcissaAxis.setLowerMargin(0.0);
    abcissaAxis.setUpperMargin(0.0);
    abcissaAxis.setTickLabelsVisible(true);
    abcissaAxis.setLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));
    abcissaAxis.setTickLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));

    plot.setDomainAxis(abcissaAxis);

    for (int i = 0; i < axes.size(); i++) {
        AxisChart categoria = axes.get(i);
        addAxis(categoria.getName());

        for (int j = 0; j < categoria.configSerieList.size(); j++) {
            SimpleSeriesConfiguration cs = categoria.configSerieList.get(j);
            addSeries(categoria.getName(), cs);
        }
    }
    chart = new JFreeChart("", new Font("SansSerif", Font.BOLD, 16), plot, false);

    chart.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));

    chartPanel = new ChartPanel(chart);
    chartPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
            BorderFactory.createLineBorder(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)))));

    chartPanel.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "escape");
    chartPanel.getActionMap().put("escape", new AbstractAction() {

        @Override
        public void actionPerformed(java.awt.event.ActionEvent e) {
            for (int i = 0; i < plot.getDatasetCount(); i++) {
                XYDataset test = plot.getDataset(i);
                XYItemRenderer r = plot.getRenderer(i);
                r.removeAnnotations();
            }
        }
    });

    chartPanel.addChartMouseListener(cml = new ChartMouseListener() {
        @Override
        public void chartMouseClicked(ChartMouseEvent event) {
        }

        @Override
        public void chartMouseMoved(ChartMouseEvent event) {
            try {
                XYItemEntity xyitem = (XYItemEntity) event.getEntity(); // get clicked entity
                XYDataset dataset = (XYDataset) xyitem.getDataset(); // get data set    
                double x = dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem());
                double y = dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem());

                final XYPlot plot = chart.getXYPlot();
                for (int i = 0; i < plot.getDatasetCount(); i++) {
                    XYDataset test = plot.getDataset(i);
                    XYItemRenderer r = plot.getRenderer(i);
                    r.removeAnnotations();
                    if (test == dataset) {
                        NumberAxis ejeOrdenada = AxesList.get(i);
                        double y_max = ejeOrdenada.getUpperBound();
                        double y_min = ejeOrdenada.getLowerBound();
                        double x_max = abcissaAxis.getUpperBound();
                        double x_min = abcissaAxis.getLowerBound();
                        double angulo;
                        if (y > (y_max + y_min) / 2 && x > (x_max + x_min) / 2) {
                            angulo = 3.0 * Math.PI / 4.0;
                        } else if (y > (y_max + y_min) / 2 && x < (x_max + x_min) / 2) {
                            angulo = 1.0 * Math.PI / 4.0;
                        } else if (y < (y_max + y_min) / 2 && x < (x_max + x_min) / 2) {
                            angulo = 7.0 * Math.PI / 4.0;
                        } else {
                            angulo = 5.0 * Math.PI / 4.0;
                        }

                        CircleDrawer cd = new CircleDrawer((Color) r.getSeriesPaint(xyitem.getSeriesIndex()),
                                new BasicStroke(2.0f), null);
                        //XYAnnotation bestBid = new XYDrawableAnnotation(dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()), dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), 11, 11, cd);
                        String txt = "X:" + abcissaFormat.format(x) + ", Y:" + ordinateFormat.format(y);
                        XYPointerAnnotation anotacion = new XYPointerAnnotation(txt,
                                dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()),
                                dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), angulo);
                        anotacion.setTipRadius(10.0);
                        anotacion.setBaseRadius(35.0);
                        anotacion.setFont(new Font("SansSerif", Font.PLAIN, 10));

                        if (Long.parseLong((strChartBackgroundColor.replace("#", "")), 16) > 0xffffff / 2) {
                            anotacion.setPaint(Color.black);
                            anotacion.setArrowPaint(Color.black);
                        } else {
                            anotacion.setPaint(Color.white);
                            anotacion.setArrowPaint(Color.white);
                        }

                        //bestBid.setPaint((Color) r.getSeriesPaint(xyitem.getSeriesIndex()));
                        r.addAnnotation(anotacion);
                    }
                }

                //LabelValorVariable.setSize(LabelValorVariable.getPreferredSize());
            } catch (NullPointerException | ClassCastException ex) {

            }
        }
    });

    chartPanel.setPopupMenu(null);
    chartPanel.setBackground(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));

    SwingNode sn = new SwingNode();
    sn.setContent(chartPanel);
    chartFrame = new VBox();
    chartFrame.getChildren().addAll(sn, legendFrame);
    VBox.setVgrow(sn, Priority.ALWAYS);
    VBox.setVgrow(legendFrame, Priority.NEVER);

    chartFrame.getStylesheets().addAll(SwingChart.class.getResource("overlay-chart.css").toExternalForm());

    legendFrame.setStyle("marco: " + strBackgroundColor + ";-fx-background-color: marco;");

    MenuItem mi;
    mi = new MenuItem("Print");
    mi.setOnAction((ActionEvent t) -> {
        print(chartFrame);
    });
    contextMenuList.add(mi);

    sn.setOnMouseClicked((MouseEvent t) -> {
        if (menu != null) {
            menu.hide();
        }
        if (t.getClickCount() == 2) {
            backgroundEdition();
        }
    });

    mi = new MenuItem("Copy to clipboard");
    mi.setOnAction((ActionEvent t) -> {
        copyClipboard(chartFrame);
    });
    contextMenuList.add(mi);

    mi = new MenuItem("Export values");
    mi.setOnAction((ActionEvent t) -> {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Export to file");
        fileChooser.getExtensionFilters()
                .addAll(new FileChooser.ExtensionFilter("Comma Separated Values", "*.csv"));

        Window w = null;
        try {
            w = parent.getScene().getWindow();
        } catch (NullPointerException e) {

        }
        File file = fileChooser.showSaveDialog(w);
        if (file != null) {
            export(file);
        }
    });
    contextMenuList.add(mi);

    chartFrame.setOnContextMenuRequested((ContextMenuEvent t) -> {
        if (menu != null) {
            menu.hide();
        }
        menu = new ContextMenu();
        menu.getItems().addAll(contextMenuList);
        menu.show(chartFrame, t.getScreenX(), t.getScreenY());
    });

}