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:lisong_mechlab.view.graphs.SustainedDpsGraph.java

/**
 * Creates and displays the {@link SustainedDpsGraph}.
 * /*ww  w.j  av  a 2 s.  c  om*/
 * @param aLoadout
 *            Which load out the diagram is for.
 * @param aXbar
 *            A {@link MessageXBar} to listen for changes to the loadout on.
 * @param aMaxSustainedDpsMetric
 *            A {@link MaxSustainedDPS} instance to use in calculation.
 */
public SustainedDpsGraph(LoadoutBase<?> aLoadout, MessageXBar aXbar, MaxSustainedDPS aMaxSustainedDpsMetric) {
    super("Max Sustained DPS over range for " + aLoadout);
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    aXbar.attach(this);

    loadout = aLoadout;
    maxSustainedDPS = aMaxSustainedDpsMetric;
    chartPanel = new ChartPanel(makechart());
    setContentPane(chartPanel);

    chartPanel.setLayout(new OverlayLayout(chartPanel));
    JButton button = new JButton(
            new OpenHelp("What is this?", "Max-sustained-dps-graph", KeyStroke.getKeyStroke('w')));
    button.setMargin(new Insets(5, 5, 5, 5));
    button.setFocusable(false);
    button.setAlignmentX(Component.RIGHT_ALIGNMENT);
    button.setAlignmentY(Component.TOP_ALIGNMENT);
    chartPanel.add(button);

    setIconImage(ProgramInit.programIcon);
    setSize(800, 600);
    setVisible(true);
}

From source file:net.sf.mzmine.modules.visualization.neutralloss.NeutralLossPlot.java

NeutralLossPlot(NeutralLossVisualizerWindow visualizer, NeutralLossDataSet dataset, Object xAxisType) {

    super(null, true);

    this.visualizer = visualizer;

    setBackground(Color.white);/*from w w w. j av  a 2s  . co m*/
    setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));

    NumberFormat rtFormat = MZmineCore.getConfiguration().getRTFormat();
    NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();

    // set the X axis (retention time) properties
    NumberAxis xAxis;
    if (xAxisType.equals(NeutralLossParameters.xAxisPrecursor)) {
        xAxis = new NumberAxis("Precursor m/z");
        xAxis.setNumberFormatOverride(mzFormat);
    } else {
        xAxis = new NumberAxis("Retention time");
        xAxis.setNumberFormatOverride(rtFormat);
    }
    xAxis.setUpperMargin(0);
    xAxis.setLowerMargin(0);
    xAxis.setAutoRangeIncludesZero(false);

    // set the Y axis (intensity) properties
    NumberAxis yAxis = new NumberAxis("Neutral loss (Da)");
    yAxis.setAutoRangeIncludesZero(false);
    yAxis.setNumberFormatOverride(mzFormat);
    yAxis.setUpperMargin(0);
    yAxis.setLowerMargin(0);

    // set the renderer properties
    defaultRenderer = new NeutralLossDataPointRenderer(false, true);
    defaultRenderer.setTransparency(0.4f);
    setSeriesColorRenderer(0, pointColor, dataPointsShape);
    setSeriesColorRenderer(1, searchPrecursorColor, dataPointsShape2);
    setSeriesColorRenderer(2, searchNeutralLossColor, dataPointsShape2);

    // tooltips
    defaultRenderer.setBaseToolTipGenerator(dataset);

    // set the plot properties
    plot = new XYPlot(dataset, xAxis, yAxis, defaultRenderer);
    plot.setBackgroundPaint(Color.white);
    plot.setRenderer(defaultRenderer);
    plot.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD);

    // chart properties
    chart = new JFreeChart("", titleFont, plot, false);
    chart.setBackgroundPaint(Color.white);

    setChart(chart);

    // title
    chartTitle = chart.getTitle();
    chartTitle.setMargin(5, 0, 0, 0);
    chartTitle.setFont(titleFont);

    // disable maximum size (we don't want scaling)
    setMaximumDrawWidth(Integer.MAX_VALUE);
    setMaximumDrawHeight(Integer.MAX_VALUE);

    // set crosshair (selection) properties
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);
    plot.setDomainCrosshairPaint(crossHairColor);
    plot.setRangeCrosshairPaint(crossHairColor);
    plot.setDomainCrosshairStroke(crossHairStroke);
    plot.setRangeCrosshairStroke(crossHairStroke);

    plot.addRangeMarker(new ValueMarker(0));

    // set focusable state to receive key events
    setFocusable(true);

    // register key handlers
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke("SPACE"), visualizer, "SHOW_SPECTRUM");

    // add items to popup menu
    JPopupMenu popupMenu = getPopupMenu();
    popupMenu.addSeparator();

    JMenuItem highLightPrecursorRange = new JMenuItem("Highlight precursor m/z range...");
    highLightPrecursorRange.addActionListener(visualizer);
    highLightPrecursorRange.setActionCommand("HIGHLIGHT_PRECURSOR");
    popupMenu.add(highLightPrecursorRange);

    JMenuItem highLightNeutralLossRange = new JMenuItem("Highlight neutral loss m/z range...");
    highLightNeutralLossRange.addActionListener(visualizer);
    highLightNeutralLossRange.setActionCommand("HIGHLIGHT_NEUTRALLOSS");
    popupMenu.add(highLightNeutralLossRange);

}

From source file:JDAC.JDAC.java

public JDAC() {
    setTitle("JDAC");

    ImageIcon img = new ImageIcon("logo.png");
    setIconImage(img.getImage());// www  .ja va2s  .co m

    //setLayout(new FlowLayout());

    mDataset = createDataset("A");

    mChart = ChartFactory.createXYLineChart("Preview", "Time (ms)", "Value", mDataset, PlotOrientation.VERTICAL,
            false, true, false);

    mLastChart = ChartFactory.createXYLineChart("Last n values", "Time (ms)", "Value", createLastDataset("B"),
            PlotOrientation.VERTICAL, false, true, false);
    mChart.getXYPlot().getDomainAxis().setLowerMargin(0);
    mChart.getXYPlot().getDomainAxis().setUpperMargin(0);
    mLastChart.getXYPlot().getDomainAxis().setLowerMargin(0);
    mLastChart.getXYPlot().getDomainAxis().setUpperMargin(0);

    ChartPanel chartPanel = new ChartPanel(mChart);
    ChartPanel chartLastPanel = new ChartPanel(mLastChart);
    //chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) );

    XYPlot plot = mChart.getXYPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesPaint(0, Color.GREEN);
    renderer.setSeriesStroke(0, new BasicStroke(1.0f));
    plot.setRenderer(renderer);

    XYPlot lastPlot = mLastChart.getXYPlot();
    XYLineAndShapeRenderer lastRenderer = new XYLineAndShapeRenderer();
    lastRenderer.setSeriesPaint(0, Color.RED);
    lastRenderer.setSeriesStroke(0, new BasicStroke(1.0f));
    lastPlot.setRenderer(lastRenderer);

    resetChartButton = new JButton("Reset");
    resetChartButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            resetChart();
        }
    });

    mMenuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    JMenu sensorMenu = new JMenu("Sensor");
    JMenu deviceMenu = new JMenu("Device");
    portSubMenu = new JMenu("Port");
    JMenu helpMenu = new JMenu("Help");

    serialStatusLabel = new JLabel("Disconnected");
    statusLabel = new JLabel("Ready");
    clearStatus = new LabelClear(statusLabel);
    clearStatus.resetTime();

    connectButton = new JMenuItem("Connect");
    disconnectButton = new JMenuItem("Disconnect");
    startButton = new JButton("Start");
    stopButton = new JButton("Stop");
    scanButton = new JMenuItem("Refresh port list");
    exportCSVButton = new JMenuItem("Export data to CSV");
    exportCSVButton.setAccelerator(KeyStroke.getKeyStroke("control S"));
    exportCSVButton.setMnemonic(KeyEvent.VK_S);
    exportPNGButton = new JMenuItem("Export chart to PNG");

    JPanel optionsPanel = new JPanel(new BorderLayout());

    JMenuItem exitItem = new JMenuItem("Exit");
    exitItem.setAccelerator(KeyStroke.getKeyStroke("control X"));
    exitItem.setMnemonic(KeyEvent.VK_X);

    JMenuItem aboutItem = new JMenuItem("About");
    JMenuItem helpItem = new JMenuItem("Help");
    JMenuItem quickStartItem = new JMenuItem("Quick start");

    lastSpinner = new JSpinner(new SpinnerNumberModel(10, 0, 1000, 1));

    ActionListener mSensorListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setSensor(e.getActionCommand());
        }
    };
    ButtonGroup sensorGroup = new ButtonGroup();
    JRadioButtonMenuItem tmpRadioButton = new JRadioButtonMenuItem("Temperature");
    sensorGroup.add(tmpRadioButton);
    sensorMenu.add(tmpRadioButton);
    tmpRadioButton.addActionListener(mSensorListener);
    tmpRadioButton = new JRadioButtonMenuItem("Distance");
    sensorGroup.add(tmpRadioButton);
    sensorMenu.add(tmpRadioButton);
    tmpRadioButton.addActionListener(mSensorListener);
    tmpRadioButton = new JRadioButtonMenuItem("Voltage");
    sensorGroup.add(tmpRadioButton);
    sensorMenu.add(tmpRadioButton);
    tmpRadioButton.addActionListener(mSensorListener);
    tmpRadioButton = new JRadioButtonMenuItem("Generic");
    tmpRadioButton.setSelected(true);
    setSensor("Generic");
    sensorGroup.add(tmpRadioButton);
    sensorMenu.add(tmpRadioButton);
    tmpRadioButton.addActionListener(mSensorListener);

    connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (selectedPortName == null) {
                setStatus("No port selected");
                return;
            }
            connect(selectedPortName);
        }
    });
    disconnectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            serialStatusLabel.setText("Disconnecting...");
            if (serialPort == null) {
                serialStatusLabel.setText("Disconnected");
                serialConnected = false;
                return;
            }

            stopCollect();
            disconnect();
        }
    });
    scanButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            searchForPorts();
        }
    });
    exportCSVButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            saveData();
        }
    });
    exportPNGButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            exportPNG();
        }
    });
    startButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            startCollect();
        }
    });
    stopButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            stopCollect();
        }
    });
    lastSpinner.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            numLastValues = (Integer) lastSpinner.getValue();
            updateLastTitle();
        }
    });
    updateLastTitle();
    exitItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    helpItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new HelpFrame();
        }
    });
    aboutItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new AboutFrame();
        }
    });
    quickStartItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new StartFrame();
        }
    });

    fileMenu.add(exportCSVButton);
    fileMenu.add(exportPNGButton);
    fileMenu.addSeparator();
    fileMenu.add(exitItem);
    deviceMenu.add(connectButton);
    deviceMenu.add(disconnectButton);
    deviceMenu.addSeparator();
    deviceMenu.add(portSubMenu);
    deviceMenu.add(scanButton);
    helpMenu.add(quickStartItem);
    helpMenu.add(helpItem);
    helpMenu.add(aboutItem);

    mMenuBar.add(fileMenu);
    mMenuBar.add(sensorMenu);
    mMenuBar.add(deviceMenu);
    mMenuBar.add(helpMenu);

    JPanel controlsPanel = new JPanel();
    controlsPanel.add(startButton);
    controlsPanel.add(stopButton);
    controlsPanel.add(resetChartButton);
    optionsPanel.add(controlsPanel, BorderLayout.LINE_START);

    JPanel lastPanel = new JPanel(new FlowLayout());
    lastPanel.add(new JLabel("Shown values: "));
    lastPanel.add(lastSpinner);
    optionsPanel.add(lastPanel);

    JPanel serialPanel = new JPanel(new FlowLayout());
    serialPanel.add(serialStatusLabel);
    optionsPanel.add(serialPanel, BorderLayout.LINE_END);

    add(optionsPanel, BorderLayout.PAGE_START);

    JPanel mainPanel = new JPanel(new GridLayout(0, 2));
    mainPanel.add(chartPanel);
    mainPanel.add(chartLastPanel);
    add(mainPanel);

    add(statusLabel, BorderLayout.PAGE_END);
    setJMenuBar(mMenuBar);

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            dispose();
        }
    });

    setSize(800, 800);
    pack();
    new StartFrame();

    //center on screen
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - getWidth()) / 2);
    int y = (int) ((dimension.getHeight() - getHeight()) / 2);
    setLocation(x, y);

    setVisible(true);
}

From source file:net.sf.mzmine.modules.visualization.spectra.SpectraPlot.java

public SpectraPlot(ActionListener masterPlot) {

    super(null, true);

    setBackground(Color.white);//  w  w w  .  j  av a  2  s.  c  o  m
    setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));

    // initialize the chart by default time series chart from factory
    chart = ChartFactory.createXYLineChart("", // title
            "m/z", // x-axis label
            "Intensity", // y-axis label
            null, // data set
            PlotOrientation.VERTICAL, // orientation
            true, // isotopeFlag, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );
    chart.setBackgroundPaint(Color.white);
    setChart(chart);

    // title
    chartTitle = chart.getTitle();
    chartTitle.setMargin(5, 0, 0, 0);
    chartTitle.setFont(titleFont);

    chartSubTitle = new TextTitle();
    chartSubTitle.setFont(subTitleFont);
    chartSubTitle.setMargin(5, 0, 0, 0);
    chart.addSubtitle(chartSubTitle);

    // legend constructed by ChartFactory
    LegendTitle legend = chart.getLegend();
    legend.setItemFont(legendFont);
    legend.setFrame(BlockBorder.NONE);

    // disable maximum size (we don't want scaling)
    setMaximumDrawWidth(Integer.MAX_VALUE);
    setMaximumDrawHeight(Integer.MAX_VALUE);
    setMinimumDrawHeight(0);

    // set the plot properties
    plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));

    // set rendering order
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    // set grid properties
    plot.setDomainGridlinePaint(gridColor);
    plot.setRangeGridlinePaint(gridColor);

    // set crosshair (selection) properties
    plot.setDomainCrosshairVisible(false);
    plot.setRangeCrosshairVisible(false);

    NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    NumberFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();

    // set the X axis (retention time) properties
    NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
    xAxis.setNumberFormatOverride(mzFormat);
    xAxis.setUpperMargin(0.001);
    xAxis.setLowerMargin(0.001);
    xAxis.setTickLabelInsets(new RectangleInsets(0, 0, 20, 20));

    // set the Y axis (intensity) properties
    NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setNumberFormatOverride(intensityFormat);

    // set focusable state to receive key events
    setFocusable(true);

    // register key handlers
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke("LEFT"), masterPlot, "PREVIOUS_SCAN");
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke("RIGHT"), masterPlot, "NEXT_SCAN");
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke('+'), this, "ZOOM_IN");
    GUIUtils.registerKeyHandler(this, KeyStroke.getKeyStroke('-'), this, "ZOOM_OUT");

    // add items to popup menu
    if (masterPlot instanceof SpectraVisualizerWindow) {
        JPopupMenu popupMenu = getPopupMenu();

        popupMenu.addSeparator();

        GUIUtils.addMenuItem(popupMenu, "Toggle centroid/continuous mode", masterPlot, "TOGGLE_PLOT_MODE");
        GUIUtils.addMenuItem(popupMenu, "Toggle displaying of data points in continuous mode", masterPlot,
                "SHOW_DATA_POINTS");
        GUIUtils.addMenuItem(popupMenu, "Toggle displaying of peak values", masterPlot, "SHOW_ANNOTATIONS");
        GUIUtils.addMenuItem(popupMenu, "Toggle displaying of picked peaks", masterPlot, "SHOW_PICKED_PEAKS");

        popupMenu.addSeparator();

        GUIUtils.addMenuItem(popupMenu, "Set axes range", masterPlot, "SETUP_AXES");

        GUIUtils.addMenuItem(popupMenu, "Set same range to all windows", masterPlot, "SET_SAME_RANGE");

        popupMenu.addSeparator();

        GUIUtils.addMenuItem(popupMenu, "Add isotope pattern", masterPlot, "ADD_ISOTOPE_PATTERN");
    }

}

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

@Override
public void addEnterPressListener(EnterPressListener listener) {
    Preconditions.checkNotNullArgument(listener);

    if (!enterPressListeners.contains(listener)) {
        enterPressListeners.add(listener);
    }/*from ww  w.  ja v a 2s  .c om*/

    if (!enterPressInitialized) {
        impl.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
        impl.getActionMap().put("enter", new ValidationAwareAction() {
            @Override
            public void actionPerformedAfterValidation(ActionEvent e) {
                EnterPressEvent event = new EnterPressEvent(DesktopTextField.this);
                for (EnterPressListener enterPressListener : new ArrayList<>(enterPressListeners)) {
                    enterPressListener.enterPressed(event);
                }
            }
        });
        enterPressInitialized = true;
    }
}

From source file:eu.ggnet.dwoss.receipt.unit.UnitView.java

public UnitView(Window window) {
    super(window);
    initComponents();/*w ww  . ja  va2 s.  c  o m*/
    setModalityType(ModalityType.APPLICATION_MODAL);
    setLocationRelativeTo(window);
    Client.lookup(UserPreferences.class).loadLocation(this);
    // Setting the change also in the subcomponent. FocusListener does not work completely.
    mfgDateChooser.addPropertyChangeListener(mfgProperty);
    mfgDateChooser.getDateEditor().getUiComponent().addPropertyChangeListener(mfgProperty);

    warrantyTillChooser.addPropertyChangeListener(warrantyProperty);
    warrantyTillChooser.getDateEditor().getUiComponent().addPropertyChangeListener(warrantyProperty);

    editRefurbishedIdButton.setEnabled(false);
    equipmentTable.setModel(equipmentModel);
    equipmentModel.setTable(equipmentTable);
    commentTable.setModel(commentModel);
    commentModel.setTable(commentTable);
    internalCommentTable.setModel(internalCommentModel);
    internalCommentModel.setTable(internalCommentTable);

    conditionController = new ComboBoxController<>(unitStateBox, UniqueUnit.Condition.values());
    warrantyController = new ComboBoxController<>(warrantyTypeChooser, Warranty.values());
    warrantyTypeChooser.setRenderer(new NamedEnumCellRenderer());
    unitStateBox.setRenderer(new NamedEnumCellRenderer());
    unitStateBox.setModel(new DefaultComboBoxModel(UniqueUnit.Condition.values()));

    refurbishedIdField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, new HashSet<>(
            Arrays.asList(KeyStroke.getKeyStroke("pressed ENTER"), KeyStroke.getKeyStroke("pressed TAB"))));
    serialField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, new HashSet<>(
            Arrays.asList(KeyStroke.getKeyStroke("pressed ENTER"), KeyStroke.getKeyStroke("pressed TAB"))));

    UiUtil.forwardTab(partNoField, unitStateBox, internalCommentArea, commentArea);
    UiUtil.backwardTab(refurbishedIdField, serialField, partNoField, unitStateBox);

    UiUtil.spaceSelection(equipmentTable);
    UiUtil.spaceSelection(internalCommentTable);
    UiUtil.spaceSelection(commentTable);

    refurbishedIdField.requestFocus();
    contractorBox.setRenderer(new NamedEnumCellRenderer());
    contractorBox.setModel(new DefaultComboBoxModel(TradeName.getManufacturers().toArray()));
}

From source file:net.sf.jabref.gui.fieldeditors.FileListEditor.java

public FileListEditor(JabRefFrame frame, BibDatabaseContext databaseContext, String fieldName, String content,
        EntryEditor entryEditor) {/*from w w w .j a  va  2s  .co  m*/
    this.frame = frame;
    this.databaseContext = databaseContext;
    this.fieldName = fieldName;
    this.entryEditor = entryEditor;
    label = new FieldNameLabel(fieldName);
    tableModel = new FileListTableModel();
    setText(content);
    setModel(tableModel);
    JScrollPane sPane = new JScrollPane(this);
    setTableHeader(null);
    addMouseListener(new TableClickListener());

    JButton add = new JButton(IconTheme.JabRefIcon.ADD_NOBOX.getSmallIcon());
    add.setToolTipText(Localization.lang("New file link (INSERT)"));
    JButton remove = new JButton(IconTheme.JabRefIcon.REMOVE_NOBOX.getSmallIcon());
    remove.setToolTipText(Localization.lang("Remove file link (DELETE)"));
    JButton up = new JButton(IconTheme.JabRefIcon.UP.getSmallIcon());

    JButton down = new JButton(IconTheme.JabRefIcon.DOWN.getSmallIcon());
    auto = new JButton(Localization.lang("Get fulltext"));
    JButton download = new JButton(Localization.lang("Download from URL"));
    add.setMargin(new Insets(0, 0, 0, 0));
    remove.setMargin(new Insets(0, 0, 0, 0));
    up.setMargin(new Insets(0, 0, 0, 0));
    down.setMargin(new Insets(0, 0, 0, 0));
    add.addActionListener(e -> addEntry());
    remove.addActionListener(e -> removeEntries());
    up.addActionListener(e -> moveEntry(-1));
    down.addActionListener(e -> moveEntry(1));
    auto.addActionListener(e -> autoSetLinks());
    download.addActionListener(e -> downloadFile());

    FormBuilder builder = FormBuilder.create()
            .layout(new FormLayout("fill:pref,1dlu,fill:pref,1dlu,fill:pref", "fill:pref,fill:pref"));
    builder.add(up).xy(1, 1);
    builder.add(add).xy(3, 1);
    builder.add(auto).xy(5, 1);
    builder.add(down).xy(1, 2);
    builder.add(remove).xy(3, 2);
    builder.add(download).xy(5, 2);
    panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(sPane, BorderLayout.CENTER);
    panel.add(builder.getPanel(), BorderLayout.EAST);

    TransferHandler transferHandler = new FileListEditorTransferHandler(frame, entryEditor, null);
    setTransferHandler(transferHandler);
    panel.setTransferHandler(transferHandler);

    // Add an input/action pair for deleting entries:
    getInputMap().put(KeyStroke.getKeyStroke("DELETE"), "delete");
    getActionMap().put("delete", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            int row = getSelectedRow();
            removeEntries();
            row = Math.min(row, getRowCount() - 1);
            if (row >= 0) {
                setRowSelectionInterval(row, row);
            }
        }
    });

    // Add an input/action pair for inserting an entry:
    getInputMap().put(KeyStroke.getKeyStroke("INSERT"), "insert");
    getActionMap().put("insert", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            addEntry();
        }
    });

    // Add input/action pair for moving an entry up:
    getInputMap().put(Globals.getKeyPrefs().getKey(KeyBinding.FILE_LIST_EDITOR_MOVE_ENTRY_UP), "move up");
    getActionMap().put("move up", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            moveEntry(-1);
        }
    });

    // Add input/action pair for moving an entry down:
    getInputMap().put(Globals.getKeyPrefs().getKey(KeyBinding.FILE_LIST_EDITOR_MOVE_ENTRY_DOWN), "move down");
    getActionMap().put("move down", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            moveEntry(1);
        }
    });

    JMenuItem openLink = new JMenuItem(Localization.lang("Open"));
    menu.add(openLink);
    openLink.addActionListener(e -> openSelectedFile());

    JMenuItem openFolder = new JMenuItem(Localization.lang("Open folder"));
    menu.add(openFolder);
    openFolder.addActionListener(e -> {
        int row = getSelectedRow();
        if (row >= 0) {
            FileListEntry entry = tableModel.getEntry(row);
            try {
                String path = "";
                // absolute path
                if (Paths.get(entry.link).isAbsolute()) {
                    path = Paths.get(entry.link).toString();
                } else {
                    // relative to file folder
                    for (String folder : databaseContext.getFileDirectory()) {
                        Path file = Paths.get(folder, entry.link);
                        if (Files.exists(file)) {
                            path = file.toString();
                            break;
                        }
                    }
                }
                if (!path.isEmpty()) {
                    JabRefDesktop.openFolderAndSelectFile(path);
                } else {
                    JOptionPane.showMessageDialog(frame, Localization.lang("File not found"),
                            Localization.lang("Error"), JOptionPane.ERROR_MESSAGE);
                }
            } catch (IOException ex) {
                LOGGER.debug("Cannot open folder", ex);
            }
        }
    });

    JMenuItem rename = new JMenuItem(Localization.lang("Move/Rename file"));
    menu.add(rename);
    rename.addActionListener(new MoveFileAction(frame, entryEditor, this, false));

    JMenuItem moveToFileDir = new JMenuItem(Localization.lang("Move file to file directory"));
    menu.add(moveToFileDir);
    moveToFileDir.addActionListener(new MoveFileAction(frame, entryEditor, this, true));

    JMenuItem deleteFile = new JMenuItem(Localization.lang("Delete local file"));
    menu.add(deleteFile);
    deleteFile.addActionListener(e -> {
        int row = getSelectedRow();
        // no selection
        if (row != -1) {

            FileListEntry entry = tableModel.getEntry(row);
            // null if file does not exist
            Optional<File> file = FileUtil.expandFilename(databaseContext, entry.link);

            // transactional delete and unlink
            try {
                if (file.isPresent()) {
                    Files.delete(file.get().toPath());
                }
                removeEntries();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(frame, Localization.lang("File permission error"),
                        Localization.lang("Cannot delete file"), JOptionPane.ERROR_MESSAGE);
                LOGGER.warn("File permission error while deleting: " + entry.link, ex);
            }
        }
    });
    adjustColumnWidth();
}

From source file:com.haulmont.cuba.desktop.sys.DesktopWindowManager.java

public void setTabsPane(final JTabbedPane tabsPane) {
    this.tabsPane = tabsPane;

    // todo move to config
    tabsPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("control W"),
            "closeTab");
    tabsPane.getActionMap().put("closeTab", new ValidationAwareAction() {
        @Override//from   ww  w.  j  a v a  2 s .  c  o m
        public void actionPerformedAfterValidation(ActionEvent e) {
            closeTab((JComponent) tabsPane.getSelectedComponent());
        }
    });
}

From source file:com.github.benchdoos.weblocopener.weblocOpener.gui.EditDialog.java

private void initTextField(String pathToEditingFile) {
    textField.addMouseListener(new ClickListener() {
        @Override/*from   www  . j a  v  a  2s .c  om*/
        public void doubleClick(MouseEvent e) {
            textField.selectAll();
        }
    });

    textField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent e) {
        }

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

        @Override
        public void removeUpdate(DocumentEvent e) {
            updateTextFont();
        }

        private void updateTextFont() {
            UrlValidator urlValidator = new UrlValidator();
            if (urlValidator.isValid(textField.getText())) {
                if (textField != null) {
                    setTextFieldFont(textField.getFont(), TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
                    textField.setForeground(Color.BLUE);
                }
            } else {
                if (textField != null) {
                    setTextFieldFont(textField.getFont(), TextAttribute.UNDERLINE, -1);
                    textField.setForeground(Color.BLACK);
                }
            }
        }

    });

    UndoManager undoManager = new UndoManager();
    textField.getDocument().addUndoableEditListener(new UndoableEditListener() {

        public void undoableEditHappened(UndoableEditEvent evt) {
            undoManager.addEdit(evt.getEdit());
        }

    });

    textField.getActionMap().put("Undo", new AbstractAction("Undo") {
        public void actionPerformed(ActionEvent evt) {
            try {
                if (undoManager.canUndo()) {
                    undoManager.undo();
                }
            } catch (CannotUndoException e) {
            }
        }
    });

    textField.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");

    textField.getActionMap().put("Redo", new AbstractAction("Redo") {
        public void actionPerformed(ActionEvent evt) {
            try {
                if (undoManager.canRedo()) {
                    undoManager.redo();
                }
            } catch (CannotRedoException e) {
            }
        }
    });

    textField.getInputMap().put(KeyStroke.getKeyStroke("control shift Z"), "Redo");

    fillTextField(pathToEditingFile);
}

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

private void init() {
    setupPopupMenu();/*from w w  w  . ja  v a 2 s.c o m*/

    addButton.addActionListener(actionEvent -> {
        AddFileDialog addDialog = new AddFileDialog();
        addDialog.setDirectoryPath(preferences.getCurrentStyle());
        addDialog.setVisible(true);
        addDialog.getFileName().ifPresent(fileName -> {
            if (loader.addStyleIfValid(fileName)) {
                preferences.setCurrentStyle(fileName);
            }
        });
        updateStyles();

    });
    addButton.setToolTipText(Localization.lang("Add style file"));

    removeButton.addActionListener(removeAction);
    removeButton.setToolTipText(Localization.lang("Remove style"));

    // Create a preview panel for previewing styles
    // Must be done before creating the table to avoid NPEs
    preview = new PreviewPanel(null, null, "");
    // Use the test entry from the Preview settings tab in Preferences:
    preview.setEntry(prevEntry);

    setupTable();
    updateStyles();

    // Build dialog
    diag = new JDialog(frame, Localization.lang("Select style"), true);

    FormBuilder builder = FormBuilder.create();
    builder.layout(new FormLayout("fill:pref:grow, 4dlu, left:pref, 4dlu, left:pref",
            "pref, 4dlu, 100dlu:grow, 4dlu, pref, 4dlu, fill:100dlu"));
    builder.add(Localization.lang("Select one of the available styles or add a style file from disk.")).xyw(1,
            1, 5);
    builder.add(new JScrollPane(table)).xyw(1, 3, 5);
    builder.add(addButton).xy(3, 5);
    builder.add(removeButton).xy(5, 5);
    builder.add(preview).xyw(1, 7, 5);
    builder.padding("5dlu, 5dlu, 5dlu, 5dlu");

    diag.add(builder.getPanel(), BorderLayout.CENTER);

    AbstractAction okListener = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent event) {
            if ((table.getRowCount() == 0) || (table.getSelectedRowCount() == 0)) {
                JOptionPane.showMessageDialog(diag, Localization.lang("You must select a valid style file."),
                        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();

    PositionWindow pw = new PositionWindow(diag, JabRefPreferences.STYLES_POS_X, JabRefPreferences.STYLES_POS_Y,
            JabRefPreferences.STYLES_SIZE_X, JabRefPreferences.STYLES_SIZE_Y);
    pw.setWindowPosition();
}