Example usage for javax.swing AbstractAction AbstractAction

List of usage examples for javax.swing AbstractAction AbstractAction

Introduction

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

Prototype

public AbstractAction() 

Source Link

Document

Creates an Action .

Usage

From source file:edu.ucla.stat.SOCR.chart.Chart.java

/**
 * Add customized table actions. //from   w w w . jav a2 s  .  c  om
 * Clicking  tab in the last cell will add one new column. 
 * Clicking return in the last cell will add one new row.
 *
 */
protected void hookTableAction() {

    //Tab--add column
    String actionName = "selectNextColumnCell";
    final Action tabAction = dataTable.getActionMap().get(actionName);
    Action myAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            //if (dataTable.isEditing() && isLastCell()) {
            if (isLastCell()) {
                //resetTableColumns(dataTable.getColumnCount()+1);
                appendTableColumns(1);
            } else
                tabAction.actionPerformed(e);
        }
    };
    dataTable.getActionMap().put(actionName, myAction);

    //Enter--append row
    String actionName2 = "selectNextRowCell";
    final Action enterAction = dataTable.getActionMap().get(actionName2);

    Action myAction2 = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            //if (dataTable.isEditing() && isLastCell()) {
            if (isLastCell()) {
                appendTableRows(1);
            } else
                enterAction.actionPerformed(e);
        }
    };

    dataTable.getActionMap().put(actionName2, myAction2);

    /*   
       String actionName3 = "deleteSelectedData";
       final Action delAction = dataTable.getActionMap().get(actionName3);
            
       Action myAction3 = new AbstractAction() {
          public void actionPerformed(ActionEvent e) {
    if ((dataTable.getSelectedRow() >= 0) && (dataTable.getSelectedColumn() >= 0)){
       int[] rows=dataTable.getSelectedRows();
       int[] cols=dataTable.getSelectedColumns(); 
       for (int i=rows[0]; i<cols[rows.length-1]; i++)
        for (int j = cols[0]; j<cols[cols.length-1]; j++){
           dataTable.setValueAt("", i, j);
       }
    }else delAction.actionPerformed(e);
               
          }
       };
       dataTable.getActionMap().put("delete", myAction3);*/

}

From source file:net.rptools.maptool.client.ui.MapToolFrame.java

private AssetPanel createAssetPanel() {
    final AssetPanel panel = new AssetPanel("mainAssetPanel");
    panel.addImagePanelMouseListener(new MouseAdapter() {
        @Override/*from  w  w w .  ja va  2s. co m*/
        public void mouseReleased(MouseEvent e) {
            // TODO use for real popup logic
            //            if (SwingUtilities.isLeftMouseButton(e)) {
            //               if (e.getClickCount() == 2) {
            //
            //                  List<Object> idList = panel.getSelectedIds();
            //                  if (idList == null || idList.size() == 0) {
            //                     return;
            //                  }
            //
            //                  final int index = (Integer) idList.get(0);
            //                  createZone(panel.getAsset(index));
            //               }
            //            }
            if (SwingUtilities.isRightMouseButton(e) && MapTool.getPlayer().isGM()) {
                List<Object> idList = panel.getSelectedIds();
                if (idList == null || idList.size() == 0) {
                    return;
                }
                final int index = (Integer) idList.get(0);

                JPopupMenu menu = new JPopupMenu();
                menu.add(new JMenuItem(new AbstractAction() {
                    {
                        putValue(NAME, I18N.getText("action.newMap"));
                    }

                    public void actionPerformed(ActionEvent e) {
                        createZone(panel.getAsset(index));
                    }
                }));
                panel.showImagePanelPopup(menu, e.getX(), e.getY());
            }
        }

        private void createZone(Asset asset) {
            Zone zone = ZoneFactory.createZone();
            zone.setName(asset.getName());
            BufferedImage image = ImageManager.getImageAndWait(asset.getId());
            if (image.getWidth() < 200 || image.getHeight() < 200) {
                zone.setBackgroundPaint(new DrawableTexturePaint(asset));
            } else {
                zone.setMapAsset(asset.getId());
                zone.setBackgroundPaint(new DrawableColorPaint(Color.black));
            }
            MapPropertiesDialog newMapDialog = new MapPropertiesDialog(MapTool.getFrame());
            newMapDialog.setZone(zone);
            newMapDialog.setVisible(true);

            if (newMapDialog.getStatus() == MapPropertiesDialog.Status.OK) {
                MapTool.addZone(zone);
            }
        }
    });
    return panel;
}

From source file:org.broad.igv.hic.MainWindow.java

private JMenuBar createMenuBar(final JPanel hiCPanel) {

    JMenuBar menuBar = new JMenuBar();

    //======== fileMenu ========
    JMenu fileMenu = new JMenu("File");

    //---- loadMenuItem ----
    JMenuItem loadMenuItem = new JMenuItem();
    loadMenuItem.setText("Load...");
    loadMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadMenuItemActionPerformed(e);
        }/*www.j  a  v a 2  s.  c o m*/
    });
    fileMenu.add(loadMenuItem);

    //---- loadFromURL ----
    JMenuItem loadFromURL = new JMenuItem();
    JMenuItem getEigenvector = new JMenuItem();
    final JCheckBoxMenuItem viewDNAseI;

    loadFromURL.setText("Load from URL ...");
    loadFromURL.setName("loadFromURL");
    loadFromURL.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadFromURLActionPerformed(e);
        }
    });
    fileMenu.add(loadFromURL);
    fileMenu.addSeparator();

    // Pre-defined datasets.  TODO -- generate from a file
    addPredefinedLoadItems(fileMenu);

    JMenuItem saveToImage = new JMenuItem();
    saveToImage.setText("Save to image");
    saveToImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            BufferedImage image = (BufferedImage) createImage(1000, 1000);
            Graphics g = image.createGraphics();
            hiCPanel.paint(g);

            JFileChooser fc = new JFileChooser();
            fc.setSelectedFile(new File("image.png"));
            int actionDialog = fc.showSaveDialog(null);
            if (actionDialog == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (file.exists()) {
                    actionDialog = JOptionPane.showConfirmDialog(null, "Replace existing file?");
                    if (actionDialog == JOptionPane.NO_OPTION || actionDialog == JOptionPane.CANCEL_OPTION)
                        return;
                }
                try {
                    // default if they give no format or invalid format
                    String fmt = "jpg";
                    int ind = file.getName().indexOf(".");
                    if (ind != -1) {
                        String ext = file.getName().substring(ind + 1);
                        String[] strs = ImageIO.getWriterFormatNames();
                        for (String aStr : strs)
                            if (ext.equals(aStr))
                                fmt = ext;
                    }
                    ImageIO.write(image.getSubimage(0, 0, 600, 600), fmt, file);
                } catch (IOException ie) {
                    System.err.println("Unable to write " + file + ": " + ie);
                }
            }
        }
    });
    fileMenu.add(saveToImage);
    getEigenvector = new JMenuItem("Get principal eigenvector");
    getEigenvector.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            getEigenvectorActionPerformed(e);
        }
    });
    fileMenu.add(getEigenvector);
    //---- exit ----
    JMenuItem exit = new JMenuItem();
    exit.setText("Exit");
    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            exitActionPerformed(e);
        }
    });
    fileMenu.add(exit);

    menuBar.add(fileMenu);

    //======== Tracks menu ========

    JMenu tracksMenu = new JMenu("Tracks");

    viewEigenvector = new JCheckBoxMenuItem("View Eigenvector...");
    viewEigenvector.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (viewEigenvector.isSelected()) {
                if (eigenvectorTrack == null) {
                    eigenvectorTrack = new EigenvectorTrack("eigen", "Eigenvectors");
                }
                updateEigenvectorTrack();
            } else {
                trackPanel.setEigenvectorTrack(null);
                if (HiCTrackManager.getLoadedTracks().isEmpty()) {
                    trackPanel.setVisible(false);
                }
            }
        }
    });
    viewEigenvector.setEnabled(false);
    tracksMenu.add(viewEigenvector);

    JMenuItem loadItem = new JMenuItem("Load...");
    loadItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadHostedTrack(MainWindow.this);
        }

    });
    tracksMenu.add(loadItem);

    JMenuItem loadFromFileItem = new JMenuItem("Load from file...");
    loadFromFileItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadTrackFromFile(MainWindow.this);
        }

    });
    tracksMenu.add(loadFromFileItem);

    menuBar.add(tracksMenu);

    //======== Extras menu ========
    JMenu extrasMenu = new JMenu("Extras");

    JMenuItem dumpPearsons = new JMenuItem("Dump pearsons matrix ...");
    dumpPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            BasicMatrix pearsons = hic.zd.getPearsons();
            try {
                String chr1 = hic.getChromosomes()[hic.zd.getChr1()].getName();
                String chr2 = hic.getChromosomes()[hic.zd.getChr2()].getName();
                int binSize = hic.zd.getBinSize();
                File initFile = new File("pearsons_" + chr1 + "_" + "_" + chr2 + "_" + binSize + ".bin");
                File f = FileDialogUtils.chooseFile("Save pearsons", null, initFile, FileDialogUtils.SAVE);
                if (f != null) {
                    ScratchPad.dumpPearsonsBinary(pearsons, chr1, chr2, hic.zd.getBinSize(), f);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });

    JMenuItem dumpEigenvector = new JMenuItem("Dump eigenvector ...");
    dumpEigenvector.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                ScratchPad.dumpEigenvector(hic);
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(dumpEigenvector);

    JMenuItem readPearsons = new JMenuItem("Read pearsons...");
    readPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                File f = FileDialogUtils.chooseFile("Pearsons file (Yunfan format)");
                if (f != null) {
                    BasicMatrix bm = ScratchPad.readPearsons(f.getAbsolutePath());

                    hic.zd.setPearsons(bm);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(readPearsons);

    extrasMenu.add(dumpPearsons);
    menuBar.add(extrasMenu);

    return menuBar;
}

From source file:org.nuclos.client.genericobject.GenericObjectCollectController.java

private void setupKeyActionsForResultPanelVerticalScrollBar() {
    // maps the default key strokes for JTable to set the vertical scrollbar, so we can intervent:
    final InputMap inputmap = getResultTable().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, InputEvent.CTRL_MASK), "last");
    inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "nextrow");
    inputmap.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0), "nextpage");

    final JScrollBar scrlbarVertical = getResultPanel().getResultTableScrollPane().getVerticalScrollBar();
    final DefaultBoundedRangeModel model = (DefaultBoundedRangeModel) scrlbarVertical.getModel();

    getResultTable().getActionMap().put("last", new AbstractAction() {

        @Override/*from  w  w w .  j a  va 2 s  . c o m*/
        public void actionPerformed(ActionEvent ev) {
            final int iSupposedValue = model.getMaximum() - model.getExtent();
            model.setValue(iSupposedValue);
            // this causes the necessary rows to be loaded. Loading may be cancelled by the user.
            LOG.debug("NOW it's time to select the row...");
            if (model.getValue() == iSupposedValue)
                getCollectNavigationModel().selectLastElement();
        }
    });

    getResultTable().getActionMap().put("nextrow", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent ev) {
            final int iSelectedRow = getResultTable().getSelectedRow();
            final int iLastVisibleRow = TableUtils.getLastVisibleRow(getResultTable());
            if (iSelectedRow + 1 < iLastVisibleRow) {
                // next row is still visible: just select it:
                if (!getCollectNavigationModel().isLastElementSelected())
                    getCollectNavigationModel().selectNextElement();
            } else {
                // we have to move the viewport before we can select the next row:
                final int iSupposedValue = Math.min(model.getValue() + getResultTable().getRowHeight(),
                        model.getMaximum() - model.getExtent());
                model.setValue(iSupposedValue);
                // this causes the necessary rows to be loaded. Loading may be cancelled by the user.
                LOG.debug("NOW it's time to select the row...");
                if (model.getValue() == iSupposedValue)
                    if (!getCollectNavigationModel().isLastElementSelected())
                        getCollectNavigationModel().selectNextElement();
            }
        }
    });

    getResultTable().getActionMap().put("nextpage", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent ev) {
            final int iSupposedValue = Math.min(model.getValue() + model.getExtent(),
                    model.getMaximum() - model.getExtent());
            model.setValue(iSupposedValue);
            // this causes the necessary rows to be loaded. Loading may be cancelled by the user.
            LOG.debug("NOW it's time to select the row...");
            if (model.getValue() == iSupposedValue) {
                final int iShiftRowCount = (int) Math
                        .ceil((double) model.getExtent() / (double) getResultTable().getRowHeight());
                final int iRow = Math.min(
                        getResultTable().getSelectionModel().getAnchorSelectionIndex() + iShiftRowCount,
                        getResultTable().getRowCount() - 1);
                getResultTable().setRowSelectionInterval(iRow, iRow);
            }
        }
    });

    final Action actShowLogBook = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent ev) {
            cmdShowLogBook();
            getDetailsPanel().grabFocus();
        }
    };
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.SHOW_LOGBOOK, actShowLogBook,
            getDetailsPanel());

    final Action actShowStateHistory = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent ev) {
            cmdShowStateHistory();
            getDetailsPanel().grabFocus();
        }
    };
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.SHOW_STATE_HISTORIE, actShowStateHistory,
            getDetailsPanel());

    final Action actPrintCurrentGenericObject = new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent ev) {
            cmdPrintCurrentGenericObject();
            getDetailsPanel().grabFocus();
        }
    };
    KeyBindingProvider.bindActionToComponent(KeyBindingProvider.PRINT_LEASED_OBJECT,
            actPrintCurrentGenericObject, getDetailsPanel());
}

From source file:br.com.atmatech.sac.view.ViewListaAtendimento.java

private void inicializaAtalhos() {
    KeyStroke keyStrokeJBnovo = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0);
    String actionNameJBnovo = "TECLA_F1";
    InputMap inputMapJBnovo = jBnovo.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

    inputMapJBnovo.put(keyStrokeJBnovo, actionNameJBnovo);
    ActionMap actionMapJBMARCA = jBnovo.getActionMap();
    actionMapJBMARCA.put(actionNameJBnovo, acaojBnovo);

    //Atalho excluir
    KeyStroke keyStrokeJBexcluir = KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0);
    String actionNameJBexcluir = "F4";
    InputMap inputMapJBexcluir = jBexcluir.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

    inputMapJBexcluir.put(keyStrokeJBexcluir, actionNameJBexcluir);
    ActionMap actionMapJBexcluir = jBexcluir.getActionMap();
    actionMapJBexcluir.put(actionNameJBexcluir, acaoJBexcluir);

    //Atalho atualizar
    KeyStroke keyStrokeJBatualizar = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0);
    String actionNameJBatualizar = "F5";
    InputMap inputMapJBatualizar = jBpesquisa.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

    inputMapJBatualizar.put(keyStrokeJBatualizar, actionNameJBatualizar);
    ActionMap actionMapJBatualizar = jBpesquisa.getActionMap();
    actionMapJBatualizar.put(actionNameJBatualizar, acaoJBpesquisa);

    //Atalho enter
    InputMap inputMapJBenter = this.jDconsulta.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMapJBenter.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "forward");
    this.jDconsulta.getRootPane().setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMapJBenter);
    this.jDconsulta.getRootPane().getActionMap().put("forward", new AbstractAction() {
        private static final long serialVersionUID = 1L;

        @Override// www .  j a  v  a 2  s.  c o  m
        public void actionPerformed(ActionEvent e) {
            filtraChamado();
        }

    });

}

From source file:com.dfki.av.sudplan.ui.MainFrame.java

private void miSaveViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miSaveViewActionPerformed

    String defaultName = "View " + viewID;
    String name = JOptionPane.showInputDialog(this, "Enter a name for the view", defaultName);
    if (name == null) {
        log.debug("Cancled JOptionPane.");
        return;//w ww.j a v a 2  s .c om
    }
    if (name.isEmpty()) {
        String msg = "Server URL is empty";
        log.error(msg);
        name = defaultName;
    }

    WorldWindowGLCanvas worldWindow = wwPanel.getWwd();
    View view = worldWindow.getView();
    String xml = view.getRestorableState();
    log.info(xml);

    final Position eyePosition = view.getEyePosition();
    final Position centerPosition = view.getGlobe().computePositionFromPoint(view.getCenterPoint());
    log.info("Saving view: eye({}), center({})", eyePosition.toString(), centerPosition.toString());

    JMenuItem menuItem = new JMenuItem(new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            WorldWindowGLCanvas canvas = wwPanel.getWwd();
            View view = canvas.getView();
            view.setOrientation(eyePosition, centerPosition);
            canvas.redraw();
        }
    });
    menuItem.setText(name);
    mCustomViewPoints.add(menuItem);
    viewID++;
}

From source file:edu.ucla.stat.SOCR.chart.demo.SOCR_EM_MixtureModelChartDemo.java

private void addKeyEventListener() {

    // add key listener for press alt key event
    InputMap inputMap = chartPaneltest.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

    KeyStroke metaPressedStroke = KeyStroke.getKeyStroke("alt ALT");
    Action metaPressedAction = new AbstractAction() {
        public void actionPerformed(ActionEvent actionEvent) {
            if (!isPressingAlt) {
                isPressingAlt = true;/*  ww  w .j a  v a  2s .  c  o  m*/
                chartPaneltest.setIsPressingAlt(true);
                //System.out.println("key Event EMDemo set " + isPressingAlt);
            }
        }
    };
    inputMap.put(metaPressedStroke, "alt ALT");
    chartPaneltest.getActionMap().put("alt ALT", metaPressedAction);
    //System.out.println("binding EMDemo alt ALT key Event");

    KeyStroke metaReleasedStroke = KeyStroke.getKeyStroke("released ALT");

    Action metaReleasedAction = new AbstractAction() {
        public void actionPerformed(ActionEvent actionEvent) {
            //System.out.println("reseting " + isPressingAlt);
            if (isPressingAlt) {
                isPressingAlt = false;
                chartPaneltest.setIsPressingAlt(false);
                //   System.out.println("key Event EMDemo reset " + isPressingAlt);
            }
        }
    };

    inputMap.put(metaReleasedStroke, "released ALT");
    chartPaneltest.getActionMap().put("released ALT", metaReleasedAction);
    //System.out.println("binding EMDemo released ALT key Event");
}

From source file:userinterface.properties.GUIGraphHandler.java

public void defineConstantsAndPlot(Expression expr, JPanel graph, String seriesName, Boolean isNewGraph,
        boolean is2D) {

    JDialog dialog;//from   w ww. j a v  a  2  s. c  o  m
    JButton ok, cancel;
    JScrollPane scrollPane;
    ConstantPickerList constantList;
    JComboBox<String> xAxis, yAxis;

    //init everything
    dialog = new JDialog(GUIPrism.getGUI());
    dialog.setTitle("Define constants and select axes");
    dialog.setSize(500, 400);
    dialog.setLocationRelativeTo(GUIPrism.getGUI());
    dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
    dialog.setModal(true);

    constantList = new ConstantPickerList();
    scrollPane = new JScrollPane(constantList);

    xAxis = new JComboBox<String>();
    yAxis = new JComboBox<String>();

    ok = new JButton("Ok");
    ok.setMnemonic('O');
    cancel = new JButton("Cancel");
    cancel.setMnemonic('C');

    //add all components to their dedicated panels
    JPanel exprPanel = new JPanel(new FlowLayout());
    exprPanel.setBorder(new TitledBorder("Function"));
    exprPanel.add(new JLabel(expr.toString()));

    JPanel axisPanel = new JPanel();
    axisPanel.setBorder(new TitledBorder("Select axis constants"));
    axisPanel.setLayout(new BoxLayout(axisPanel, BoxLayout.Y_AXIS));
    JPanel xAxisPanel = new JPanel(new FlowLayout());
    xAxisPanel.add(new JLabel("X axis:"));
    xAxisPanel.add(xAxis);
    JPanel yAxisPanel = new JPanel(new FlowLayout());
    yAxisPanel.add(new JLabel("Y axis:"));
    yAxisPanel.add(yAxis);
    axisPanel.add(xAxisPanel);
    axisPanel.add(yAxisPanel);

    JPanel constantPanel = new JPanel(new BorderLayout());
    constantPanel.setBorder(new TitledBorder("Please define the following constants"));
    constantPanel.add(scrollPane, BorderLayout.CENTER);
    constantPanel.add(new ConstantHeader(), BorderLayout.NORTH);

    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    bottomPanel.add(ok);
    bottomPanel.add(cancel);

    //fill the axes components

    for (int i = 0; i < expr.getAllConstants().size(); i++) {

        xAxis.addItem(expr.getAllConstants().get(i));

        if (!is2D)
            yAxis.addItem(expr.getAllConstants().get(i));
    }

    if (!is2D) {
        yAxis.setSelectedIndex(1);
    }

    //fill the constants table

    for (int i = 0; i < expr.getAllConstants().size(); i++) {

        ConstantLine line = new ConstantLine(expr.getAllConstants().get(i), TypeDouble.getInstance());
        constantList.addConstant(line);

        if (!is2D) {
            if (line.getName().equals(xAxis.getSelectedItem().toString())
                    || line.getName().equals(yAxis.getSelectedItem().toString())) {

                line.doFuncEnables(false);
            } else {
                line.doFuncEnables(true);
            }
        }

    }

    //do enables

    if (is2D) {
        yAxis.setEnabled(false);
    }

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ok.doClick();
        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "cancel");
    cancel.getActionMap().put("cancel", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cancel.doClick();
        }
    });

    //add action listeners

    xAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (is2D) {
                return;
            }

            String item = xAxis.getSelectedItem().toString();

            if (item.equals(yAxis.getSelectedItem().toString())) {

                int index = yAxis.getSelectedIndex();

                if (index != yAxis.getItemCount() - 1) {
                    yAxis.setSelectedIndex(++index);
                } else {
                    yAxis.setSelectedIndex(--index);
                }

            }

            for (int i = 0; i < constantList.getNumConstants(); i++) {

                ConstantLine line = constantList.getConstantLine(i);

                if (line.getName().equals(xAxis.getSelectedItem().toString())
                        || line.getName().equals(yAxis.getSelectedItem().toString())) {

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    yAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String item = yAxis.getSelectedItem().toString();

            if (item.equals(xAxis.getSelectedItem().toString())) {

                int index = xAxis.getSelectedIndex();

                if (index != xAxis.getItemCount() - 1) {
                    xAxis.setSelectedIndex(++index);
                } else {
                    xAxis.setSelectedIndex(--index);
                }
            }

            for (int i = 0; i < constantList.getNumConstants(); i++) {

                ConstantLine line = constantList.getConstantLine(i);

                if (line.getName().equals(xAxis.getSelectedItem().toString())
                        || line.getName().equals(yAxis.getSelectedItem().toString())) {

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            try {

                constantList.checkValid();

            } catch (PrismException e2) {
                JOptionPane.showMessageDialog(dialog,
                        "<html> One or more of the defined constants are invalid. <br><br> <font color=red>Error: </font>"
                                + e2.getMessage() + "</html>",
                        "Parse Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (is2D) {

                // it will always be a parametric graph in 2d case
                ParametricGraph pGraph = (ParametricGraph) graph;

                ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString());

                if (xAxisConstant == null) {
                    //should never happen
                    JOptionPane.showMessageDialog(dialog, "The selected axis is invalid.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                double xStartValue = Double.parseDouble(xAxisConstant.getStartValue());
                double xEndValue = Double.parseDouble(xAxisConstant.getEndValue());
                double xStepValue = Double.parseDouble(xAxisConstant.getStepValue());

                int seriesCount = 0;

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getName().equals(xAxis.getSelectedItem().toString())) {
                        seriesCount++;
                    } else {

                        seriesCount += line.getTotalNumOfValues();

                    }
                }

                // if there will be too many series to be plotted, ask the user if they are sure they know what they are doing
                if (seriesCount > 10) {

                    int res = JOptionPane.showConfirmDialog(dialog,
                            "This configuration will create " + seriesCount + " series. Continue?", "Confirm",
                            JOptionPane.YES_NO_OPTION);

                    if (res == JOptionPane.NO_OPTION) {
                        return;
                    }

                }

                Values singleValuesGlobal = new Values();

                //add the single values to a global values list

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getTotalNumOfValues() == 1) {

                        double singleValue = Double.parseDouble(line.getSingleValue());
                        singleValuesGlobal.addValue(line.getName(), singleValue);
                    }
                }

                // we just have one variable so we can plot directly
                if (constantList.getNumConstants() == 1
                        || singleValuesGlobal.getNumValues() == constantList.getNumConstants() - 1) {

                    SeriesKey key = pGraph.addSeries(seriesName);

                    pGraph.hideShape(key);
                    pGraph.getXAxisSettings().setHeading(xAxis.getSelectedItem().toString());
                    pGraph.getYAxisSettings().setHeading("function");

                    for (double x = xStartValue; x <= xEndValue; x += xStepValue) {

                        double ans = -1;

                        Values vals = new Values();
                        vals.addValue(xAxis.getSelectedItem().toString(), x);

                        for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) {

                            try {
                                vals.addValue(singleValuesGlobal.getName(ii),
                                        singleValuesGlobal.getDoubleValue(ii));
                            } catch (PrismLangException e1) {
                                e1.printStackTrace();
                            }

                        }

                        try {
                            ans = expr.evaluateDouble(vals);
                        } catch (PrismLangException e1) {
                            e1.printStackTrace();
                        }

                        pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans));

                    }

                    if (isNewGraph) {
                        addGraph(pGraph);
                    }

                    dialog.dispose();
                    return;
                }

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line == xAxisConstant || singleValuesGlobal.contains(line.getName())) {
                        continue;
                    }

                    double lineStart = Double.parseDouble(line.getStartValue());
                    double lineEnd = Double.parseDouble(line.getEndValue());
                    double lineStep = Double.parseDouble(line.getStepValue());

                    for (double j = lineStart; j < lineEnd; j += lineStep) {

                        SeriesKey key = pGraph.addSeries(seriesName);
                        pGraph.hideShape(key);

                        for (double x = xStartValue; x <= xEndValue; x += xStepValue) {

                            double ans = -1;

                            Values vals = new Values();
                            vals.addValue(xAxis.getSelectedItem().toString(), x);
                            vals.addValue(line.getName(), j);

                            for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) {

                                try {
                                    vals.addValue(singleValuesGlobal.getName(ii),
                                            singleValuesGlobal.getDoubleValue(ii));
                                } catch (PrismLangException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }

                            }

                            for (int ii = 0; ii < constantList.getNumConstants(); ii++) {

                                if (constantList.getConstantLine(ii) == xAxisConstant
                                        || singleValuesGlobal
                                                .contains(constantList.getConstantLine(ii).getName())
                                        || constantList.getConstantLine(ii) == line) {

                                    continue;
                                }

                                ConstantLine temp = constantList.getConstantLine(ii);
                                double val = Double.parseDouble(temp.getStartValue());

                                vals.addValue(temp.getName(), val);
                            }

                            try {
                                ans = expr.evaluateDouble(vals);
                            } catch (PrismLangException e1) {
                                e1.printStackTrace();
                            }

                            pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans));
                        }
                    }

                }

                if (isNewGraph) {
                    addGraph(graph);
                }
            } else {

                // this will always be a parametric graph for the 3d case
                ParametricGraph3D pGraph = (ParametricGraph3D) graph;

                //add the graph to the gui
                addGraph(pGraph);

                //Get the constants we want to put on the x and y axis
                ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString());
                ConstantLine yAxisConstant = constantList.getConstantLine(yAxis.getSelectedItem().toString());

                //add the single values to a global values list

                Values singleValuesGlobal = new Values();

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getTotalNumOfValues() == 1) {

                        double singleValue = Double.parseDouble(line.getSingleValue());
                        singleValuesGlobal.addValue(line.getName(), singleValue);
                    }
                }

                pGraph.setGlobalValues(singleValuesGlobal);
                pGraph.setAxisConstants(xAxis.getSelectedItem().toString(), yAxis.getSelectedItem().toString());
                pGraph.setBounds(xAxisConstant.getStartValue(), xAxisConstant.getEndValue(),
                        yAxisConstant.getStartValue(), yAxisConstant.getEndValue());

                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        //plot the graph
                        pGraph.plot(expr.toString(), xAxis.getSelectedItem().toString(), "Function",
                                yAxis.getSelectedItem().toString());

                        //calculate the sampling rates from the step sizes as given by the user

                        int xSamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue())
                                - Double.parseDouble(xAxisConstant.getStartValue()))
                                / Double.parseDouble(xAxisConstant.getStepValue()));
                        int ySamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue())
                                - Double.parseDouble(xAxisConstant.getStartValue()))
                                / Double.parseDouble(xAxisConstant.getStepValue()));

                        pGraph.setSamplingRates(xSamples, ySamples);
                    }
                });

            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    });

    //add everything to the dialog show the dialog

    dialog.add(exprPanel);
    dialog.add(axisPanel);
    dialog.add(constantPanel);
    dialog.add(bottomPanel);
    dialog.setVisible(true);

}

From source file:org.isatools.isacreator.spreadsheet.Spreadsheet.java

/**
 * Setup the JTable with its desired characteristics
 *//*w  ww.  j  a v  a2s.co m*/
private void setupTable() {
    table = new CustomTable(spreadsheetModel);
    table.setShowGrid(true);
    table.setGridColor(Color.BLACK);
    table.setShowVerticalLines(true);
    table.setShowHorizontalLines(true);
    table.setGridColor(UIHelper.LIGHT_GREEN_COLOR);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);
    table.setAutoCreateColumnsFromModel(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.getSelectionModel().addListSelectionListener(this);
    table.getColumnModel().getSelectionModel().addListSelectionListener(this);
    table.getTableHeader().setReorderingAllowed(true);
    table.getColumnModel().addColumnModelListener(this);
    try {
        table.setDefaultRenderer(Class.forName("java.lang.Object"), new SpreadsheetCellRenderer());
    } catch (ClassNotFoundException e) {
        // ignore this error
    }

    table.addMouseListener(this);
    table.getTableHeader().addMouseMotionListener(new MouseMotionListener() {
        public void mouseDragged(MouseEvent event) {
        }

        public void mouseMoved(MouseEvent event) {
            // display a tooltip when user hovers over a column. tooltip is derived
            // from the description of a field from the TableReferenceObject.
            JTable table = ((JTableHeader) event.getSource()).getTable();
            TableColumnModel colModel = table.getColumnModel();
            int colIndex = colModel.getColumnIndexAtX(event.getX());

            // greater than 1 to account for the row no. being the first col
            if (colIndex >= 1) {
                TableColumn tc = colModel.getColumn(colIndex);
                if (tc != null) {
                    try {
                        table.getTableHeader().setToolTipText(getFieldDescription(tc));
                    } catch (Exception e) {
                        // ignore this error
                    }
                }
            }
        }
    });

    //table.getColumnModel().addColumnModelListener(this);
    InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);

    //  Override the default tab behaviour
    //  Tab to the next editable cell. When no editable cells goto next cell.
    final Action previousTabAction = table.getActionMap().get(im.get(tab));
    Action newTabAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            // maintain previous tab action procedure
            previousTabAction.actionPerformed(e);

            JTable table = (JTable) e.getSource();
            int row = table.getSelectedRow();
            int originalRow = row;
            int column = table.getSelectedColumn();
            int originalColumn = column;

            while (!table.isCellEditable(row, column)) {
                previousTabAction.actionPerformed(e);
                row = table.getSelectedRow();
                column = table.getSelectedColumn();

                //  Back to where we started, get out.
                if ((row == originalRow) && (column == originalColumn)) {
                    break;
                }
            }

            if (table.editCellAt(row, column)) {
                table.getEditorComponent().requestFocusInWindow();
            }
        }
    };

    table.getActionMap().put(im.get(tab), newTabAction);
    TableColumnModel model = table.getColumnModel();

    String previousColumnName = null;
    for (int columnIndex = 0; columnIndex < tableReferenceObject.getHeaders().size(); columnIndex++) {
        if (!model.getColumn(columnIndex).getHeaderValue().toString()
                .equals(TableReferenceObject.ROW_NO_TEXT)) {
            model.getColumn(columnIndex).setHeaderRenderer(columnRenderer);
            model.getColumn(columnIndex).setPreferredWidth(spreadsheetFunctions
                    .calcColWidths(model.getColumn(columnIndex).getHeaderValue().toString()));
            // add appropriate cell editor for cell.
            spreadsheetFunctions.addCellEditor(model.getColumn(columnIndex), previousColumnName);
            previousColumnName = model.getColumn(columnIndex).getHeaderValue().toString();
        } else {
            model.getColumn(columnIndex).setHeaderRenderer(new RowNumberCellRenderer());
        }
    }

    JTableHeader header = table.getTableHeader();
    header.setBackground(UIHelper.BG_COLOR);
    header.addMouseListener(new HeaderListener(header, columnRenderer));

    table.addNotify();
}

From source file:de.codesourcery.jasm16.ide.ui.views.SourceCodeView.java

protected final void setupKeyBindings(final JTextPane editor) {
    // 'Save' action 
    addKeyBinding(editor, KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK), new AbstractAction() {
        @Override/*from   ww  w  . j a  va  2s  . c om*/
        public void actionPerformed(ActionEvent e) {
            saveCurrentFile();
        }
    });

    // 'Underline text when pressing CTRL while hovering over an identifier' 
    editorPane.addKeyListener(new KeyAdapter() {
        private boolean isControlKey(KeyEvent e) {
            return e.getKeyCode() == KeyEvent.VK_CONTROL;
        }

        public void keyPressed(KeyEvent e) {
            if (isControlKey(e)) {
                final Point ptr = getMouseLocation();
                if (ptr != null) {
                    maybeUnderlineIdentifierAt(ptr);
                }
            }
        }

        public void keyReleased(KeyEvent e) {
            if (isControlKey(e)) {
                clearUnderlineHighlight();
            }
        };
    });

    // "Undo" action
    addKeyBinding(editor, KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK), undoAction);

    addKeyBinding(editor, KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK), redoAction);

    // 'Search' action 
    addKeyBinding(editor, KeyStroke.getKeyStroke(KeyEvent.VK_F, Event.CTRL_MASK), new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            showSearchDialog();
        }
    });

    setupKeyBindingsHook(editor);
}