Example usage for javax.swing JTable getSelectedRow

List of usage examples for javax.swing JTable getSelectedRow

Introduction

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

Prototype

@BeanProperty(bound = false)
public int getSelectedRow() 

Source Link

Document

Returns the index of the first selected row, -1 if no row is selected.

Usage

From source file:me.mayo.telnetkek.MainPanel.java

public final void setupTablePopup() {
    this.tblPlayers.addMouseListener(new MouseAdapter() {
        @Override//w w w . j  a  va 2s. c  o  m
        public void mouseReleased(final MouseEvent mouseEvent) {
            final JTable table = MainPanel.this.tblPlayers;

            final int r = table.rowAtPoint(mouseEvent.getPoint());
            if (r >= 0 && r < table.getRowCount()) {
                table.setRowSelectionInterval(r, r);
            } else {
                table.clearSelection();
            }

            final int rowindex = table.getSelectedRow();
            if (rowindex < 0) {
                return;
            }

            if ((SwingUtilities.isRightMouseButton(mouseEvent) || mouseEvent.isControlDown())
                    && mouseEvent.getComponent() instanceof JTable) {
                final PlayerInfo player = getSelectedPlayer();
                if (player != null) {
                    final JPopupMenu popup = new JPopupMenu(player.getName());

                    final JMenuItem header = new JMenuItem("Apply action to " + player.getName() + ":");
                    header.setEnabled(false);
                    popup.add(header);

                    popup.addSeparator();

                    final ActionListener popupAction = (ActionEvent actionEvent) -> {
                        Object _source = actionEvent.getSource();
                        if (_source instanceof PlayerListPopupItem_Command) {
                            final PlayerListPopupItem_Command source = (PlayerListPopupItem_Command) _source;
                            final String output = source.getCommand().buildOutput(source.getPlayer(), true);
                            MainPanel.this.getConnectionManager().sendDelayedCommand(output, true, 100);
                        } else if (_source instanceof PlayerListPopupItem) {
                            final PlayerListPopupItem source = (PlayerListPopupItem) _source;

                            final PlayerInfo _player = source.getPlayer();

                            switch (actionEvent.getActionCommand()) {
                            case "Copy IP": {
                                copyToClipboard(_player.getIp());
                                MainPanel.this.writeToConsole(
                                        new ConsoleMessage("Copied IP to clipboard: " + _player.getIp()));
                                break;
                            }
                            case "Copy Name": {
                                copyToClipboard(_player.getName());
                                MainPanel.this.writeToConsole(
                                        new ConsoleMessage("Copied name to clipboard: " + _player.getName()));
                                break;
                            }
                            case "Copy UUID": {
                                copyToClipboard(_player.getUuid());
                                MainPanel.this.writeToConsole(
                                        new ConsoleMessage("Copied UUID to clipboard: " + _player.getUuid()));
                                break;
                            }
                            }
                        }
                    };

                    TelnetKek.config.getCommands().stream().map(
                            (command) -> new PlayerListPopupItem_Command(command.getName(), player, command))
                            .map((item) -> {
                                item.addActionListener(popupAction);
                                return item;
                            }).forEach((item) -> {
                                popup.add(item);
                            });

                    popup.addSeparator();

                    JMenuItem item;

                    item = new PlayerListPopupItem("Copy Name", player);
                    item.addActionListener(popupAction);
                    popup.add(item);

                    item = new PlayerListPopupItem("Copy IP", player);
                    item.addActionListener(popupAction);
                    popup.add(item);

                    item = new PlayerListPopupItem("Copy UUID", player);
                    item.addActionListener(popupAction);
                    popup.add(item);

                    popup.show(mouseEvent.getComponent(), mouseEvent.getX(), mouseEvent.getY());
                }
            }
        }
    });
}

From source file:com.haskins.cloudtrailviewer.sidebar.AbstractChart.java

private void addTable() {

    defaultTableModel.addColumn("");
    defaultTableModel.addColumn("Property");
    defaultTableModel.addColumn("Value");

    final LegendColourRenderer cellRenderer = new LegendColourRenderer();
    final JTable table = new JTable(defaultTableModel) {

        private static final long serialVersionUID = -6272711583089149891L;

        @Override//w  w w.  j  a  v a 2 s  .  c  om
        public TableCellRenderer getCellRenderer(int row, int column) {
            if (column == 0) {
                return cellRenderer;
            }
            return super.getCellRenderer(row, column);
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };

    table.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent me) {

            JTable table = (JTable) me.getSource();
            String value = (String) defaultTableModel.getValueAt(table.getSelectedRow(), 1);

            if (me.getClickCount() == 2) {

                if (value.startsWith("i-")) {

                    Event event = null;
                    AllFilter filter = new AllFilter();
                    filter.setNeedle(value);
                    for (Event searchEvent : eventDb.getEvents()) {

                        if (filter.passesFilter(searchEvent)) {

                            event = searchEvent;
                            break;
                        }
                    }

                    if (event != null) {
                        AwsAccount account = AccountDao.getAccountByAcctNum(event.getRecipientAccountId());
                        ResourceDetailRequest request = new ResourceDetailRequest(account, event.getAwsRegion(),
                                "EC2 Instance", value);
                        ResourceDetailDialog.showDialog(CloudTrailViewer.frame, request);
                    }
                }

            } else if (me.getClickCount() == 1) {

                try {
                    eventTablePanel.setFilterString(value);
                } catch (Exception ex) {
                    LOGGER.log(Level.WARNING, "Problem responding to mouse event on chart table", ex);
                }
            }
        }
    });

    TableColumn column;
    for (int i = 0; i < 3; i++) {
        column = table.getColumnModel().getColumn(i);

        switch (i) {
        case 0:
            column.setMinWidth(15);
            column.setMaxWidth(15);
            column.setPreferredWidth(15);
            break;

        case 2:
            column.setMinWidth(70);
            column.setMaxWidth(70);
            column.setPreferredWidth(70);
            break;
        }
    }

    JScrollPane tablecrollPane = new JScrollPane(table);
    tablecrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

    this.add(tablecrollPane, BorderLayout.CENTER);
}

From source file:com.haskins.cloudtrailviewer.sidebar.EventsStats.java

private void addTable() {

    defaultTableModel.addColumn("");
    defaultTableModel.addColumn("Property");
    defaultTableModel.addColumn("Value");

    final LegendColourRenderer cellRenderer = new LegendColourRenderer();
    final JTable table = new JTable(defaultTableModel) {

        @Override/*from  ww  w  . j  a  v a  2s .c o m*/
        public TableCellRenderer getCellRenderer(int row, int column) {
            if (column == 0) {
                return cellRenderer;
            }
            return super.getCellRenderer(row, column);
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        };
    };

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {

            if (e.getFirstIndex() >= 0) {

                String value = (String) defaultTableModel.getValueAt(table.getSelectedRow(), 1);
                eventTablePanel.setFilterString(value);
            }
        }
    });

    TableColumn column;
    for (int i = 0; i < 3; i++) {
        column = table.getColumnModel().getColumn(i);

        switch (i) {
        case 0:
            column.setMinWidth(15);
            column.setMaxWidth(15);
            column.setPreferredWidth(15);
            break;

        case 2:
            column.setMinWidth(70);
            column.setMaxWidth(70);
            column.setPreferredWidth(70);
            break;
        }
    }

    JScrollPane tablecrollPane = new JScrollPane(table);
    tablecrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

    this.add(tablecrollPane, BorderLayout.CENTER);
}

From source file:net.sf.jabref.importer.ZipFileChooser.java

/**
 * New Zip file chooser.//from w ww .  ja  v a  2s .c om
 *
 * @param owner  Owner of the file chooser
 * @param zipFile  Zip-Fle to choose from, must be readable
 */
public ZipFileChooser(ImportCustomizationDialog importCustomizationDialog, ZipFile zipFile) {
    super(importCustomizationDialog, Localization.lang("Select file from ZIP-archive"), false);

    ZipFileChooserTableModel tableModel = new ZipFileChooserTableModel(zipFile,
            getSelectableZipEntries(zipFile));
    JTable table = new JTable(tableModel);
    TableColumnModel cm = table.getColumnModel();
    cm.getColumn(0).setPreferredWidth(200);
    cm.getColumn(1).setPreferredWidth(150);
    cm.getColumn(2).setPreferredWidth(100);
    JScrollPane sp = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setPreferredScrollableViewportSize(new Dimension(500, 150));
    if (table.getRowCount() > 0) {
        table.setRowSelectionInterval(0, 0);
    }

    // cancel: no entry is selected
    JButton cancelButton = new JButton(Localization.lang("Cancel"));
    cancelButton.addActionListener(e -> dispose());
    // ok: get selected class and check if it is instantiable as an importer
    JButton okButton = new JButton(Localization.lang("OK"));
    okButton.addActionListener(e -> {
        int row = table.getSelectedRow();
        if (row == -1) {
            JOptionPane.showMessageDialog(this, Localization.lang("Please select an importer."));
        } else {
            ZipFileChooserTableModel model = (ZipFileChooserTableModel) table.getModel();
            ZipEntry tempZipEntry = model.getZipEntry(row);
            CustomImporter importer = new CustomImporter();
            importer.setBasePath(model.getZipFile().getName());
            String className = tempZipEntry.getName().substring(0, tempZipEntry.getName().lastIndexOf('.'))
                    .replace("/", ".");
            importer.setClassName(className);
            try {
                ImportFormat importFormat = importer.getInstance();
                importer.setName(importFormat.getFormatName());
                importer.setCliId(importFormat.getId());
                importCustomizationDialog.addOrReplaceImporter(importer);
                dispose();
            } catch (IOException | ClassNotFoundException | InstantiationException
                    | IllegalAccessException exc) {
                LOGGER.warn("Could not instantiate importer: " + importer.getName(), exc);
                JOptionPane.showMessageDialog(this, Localization.lang("Could not instantiate %0 %1",
                        importer.getName() + ":\n", exc.getMessage()));
            }
        }
    });

    // Key bindings:
    JPanel mainPanel = new JPanel();
    //ActionMap am = mainPanel.getActionMap();
    //InputMap im = mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    //im.put(Globals.getKeyPrefs().getKey(KeyBinds.CLOSE_DIALOG), "close");
    //am.put("close", closeAction);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(sp, BorderLayout.CENTER);

    JPanel optionsPanel = new JPanel();
    optionsPanel.add(okButton);
    optionsPanel.add(cancelButton);
    optionsPanel.add(Box.createHorizontalStrut(5));

    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(optionsPanel, BorderLayout.SOUTH);
    this.setSize(getSize());
    pack();
    this.setLocationRelativeTo(importCustomizationDialog);
    new FocusRequester(table);
}

From source file:org.zaproxy.zap.extension.multiFuzz.impl.http.HttpFuzzResultDialog.java

@Override
public JXTreeTable getTable() {
    if (table == null) {
        if (model == null) {
            model = new HttpFuzzTableModel();
        }//from ww w .ja  v  a  2  s .c o m
        table = new JXTreeTable(model);
        table.setDoubleBuffered(true);
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        table.setName("HttpFuzzResultTable");
        table.setFont(new java.awt.Font("Default", java.awt.Font.PLAIN, 12));
        table.setDefaultRenderer(Pair.class, new IconTableCellRenderer());

        int[] widths = { 10, 25, 550, 30, 85, 55, 40, 70 };
        for (int i = 0, count = widths.length; i < count; i++) {
            TableColumn column = table.getColumnModel().getColumn(i);
            column.setPreferredWidth(widths[i]);
        }
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mousePressed(java.awt.event.MouseEvent e) {
                showPopupMenuIfTriggered(e);
            }

            @Override
            public void mouseReleased(java.awt.event.MouseEvent e) {
                showPopupMenuIfTriggered(e);
            }

            private void showPopupMenuIfTriggered(java.awt.event.MouseEvent e) {
                if (e.isPopupTrigger()) {
                    if (e.isPopupTrigger()) {
                        // Select list item on right click
                        JTable table = (JTable) e.getSource();
                        int row = table.rowAtPoint(e.getPoint());

                        if (!table.isRowSelected(row)) {
                            table.changeSelection(row, 0, false, false);
                        }
                        View.getSingleton().getPopupMenu().show(e.getComponent(), e.getX(), e.getY());
                    }
                }
            }

        });
        table.getSelectionModel().addListSelectionListener(new javax.swing.event.ListSelectionListener() {

            @Override
            public void valueChanged(javax.swing.event.ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    if (table.getSelectedRowCount() == 0) {
                        return;
                    }
                    final int row = table.getSelectedRow();
                    if (getEntry(row) instanceof HttpFuzzRequestRecord) {
                        final HistoryReference historyReference = ((HttpFuzzRequestRecord) getEntry(row))
                                .getHistory();
                        try {
                            getMessageInspection().setMessage(historyReference.getHttpMessage());
                        } catch (HttpMalformedHeaderException | SQLException ex) {
                            logger.error(ex.getMessage(), ex);
                        }
                    }
                    updateValues();
                    redrawDiagrams();
                }
            }
        });
    }
    table.getTableHeader().addMouseListener(new MouseListener() {
        int sortedOn = -1;

        @Override
        public void mouseReleased(MouseEvent arg0) {
        }

        @Override
        public void mousePressed(MouseEvent arg0) {
        }

        @Override
        public void mouseExited(MouseEvent arg0) {
        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            int index = table.columnAtPoint(e.getPoint());
            List<HttpFuzzRecord> list = model.getEntries();
            if (list.size() == 0) {
                return;
            }
            HttpFuzzRecordComparator comp = new HttpFuzzRecordComparator();
            comp.setFeature(index);
            if (index == sortedOn) {
                Collections.sort(list, comp);
                Collections.reverse(list);
                sortedOn = -1;
            } else {
                Collections.sort(list, comp);
                sortedOn = index;
            }
            table.updateUI();
        }
    });
    table.setRootVisible(false);
    table.setVisible(true);
    return table;
}

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

private void initTablePopupMenu() {
    JPopupMenu popupMenu = new JPopupMenu();

    JMenuItem deleteMenuItem = new JMenuItem("(D)",
            new ImageIcon(getClass().getResource("edit-delete-6.png")));
    deleteMenuItem.setMnemonic('D');
    popupMenu.add(deleteMenuItem);//from  www .j a  v a2s.  com
    deleteMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            deleteRecord();
        }
    });

    popupMenu.addSeparator();

    JMenuItem editMenuItem = new JMenuItem("(E)", new ImageIcon(getClass().getResource("edit-4.png")));
    editMenuItem.setMnemonic('E');
    popupMenu.add(editMenuItem);
    editMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Record record = model.getRecord(table.convertRowIndexToModel(table.getSelectedRow()));
            showUpdateRecordDialog(record);
        }
    });

    // ??popup menu
    table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (disable)
                return;
            JTable table = (JTable) e.getSource();
            Point point = e.getPoint();
            int row = table.rowAtPoint(point);
            int col = table.columnAtPoint(e.getPoint());
            if (SwingUtilities.isRightMouseButton(e)) {
                if (row >= 0 && col >= 0) {
                    table.setRowSelectionInterval(row, row);
                }
                popupMenu.show(e.getComponent(), e.getX(), e.getY());
            } else if (SwingUtilities.isLeftMouseButton(e)) {
                if (e.getClickCount() == 2) {
                    if (row >= 0 && col >= 0) {
                        //                            Record record = model.getRecord(table.convertRowIndexToModel(row));
                        //                            showUpdateRecordDialog(record);
                    }
                }
            }
        }

    });

    table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
            .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
    table.getActionMap().put("Enter", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            if (disable)
                return;
            //do something on JTable enter pressed
            int row = table.getSelectedRow();
            if (row >= 0) {
                Record record = model.getRecord(table.convertRowIndexToModel(row));
                showUpdateRecordDialog(record);
            }
        }
    });

}

From source file:mt.listeners.InteractiveRANSAC.java

public void CardTable() {
    this.lambdaSB = new Scrollbar(Scrollbar.HORIZONTAL, this.lambdaInt, 1, MIN_SLIDER, MAX_SLIDER + 1);

    maxSlopeSB.setValue(utility.Slicer.computeScrollbarPositionFromValue((float) maxSlope,
            (float) MIN_ABS_SLOPE, (float) MAX_ABS_SLOPE, scrollbarSize));

    maxDistSB.setValue(//from ww w . j a  v  a2  s .c  o  m
            utility.Slicer.computeScrollbarPositionFromValue(maxDist, MIN_Gap, MAX_Gap, scrollbarSize));

    minInliersSB.setValue(utility.Slicer.computeScrollbarPositionFromValue(minInliers, MIN_Inlier, MAX_Inlier,
            scrollbarSize));
    maxErrorSB.setValue(
            utility.Slicer.computeScrollbarPositionFromValue(maxError, MIN_ERROR, MAX_ERROR, scrollbarSize));

    minSlopeSB.setValue(utility.Slicer.computeScrollbarPositionFromValue((float) minSlope,
            (float) MIN_ABS_SLOPE, (float) MAX_ABS_SLOPE, scrollbarSize));

    lambdaLabel = new Label("Linearity (fraction) = " + new DecimalFormat("#.##").format(lambda), Label.CENTER);
    maxErrorLabel = new Label("Maximum Error (px) = " + new DecimalFormat("#.##").format(maxError) + "      ",
            Label.CENTER);
    minInliersLabel = new Label(
            "Minimum No. of timepoints (tp) = " + new DecimalFormat("#.##").format(minInliers), Label.CENTER);
    maxDistLabel = new Label("Maximum Gap (tp) = " + new DecimalFormat("#.##").format(maxDist), Label.CENTER);

    minSlopeLabel = new Label("Min. Segment Slope (px/tp) = " + new DecimalFormat("#.##").format(minSlope),
            Label.CENTER);
    maxSlopeLabel = new Label("Max. Segment Slope (px/tp) = " + new DecimalFormat("#.##").format(maxSlope),
            Label.CENTER);
    maxResLabel = new Label(
            "MT is rescued if the start of event# i + 1 > start of event# i by px =  " + this.restolerance,
            Label.CENTER);

    CardLayout cl = new CardLayout();
    Object[] colnames = new Object[] { "Track File", "Growth velocity", "Shrink velocity", "Growth events",
            "Shrink events", "fcat", "fres", "Error" };

    Object[][] rowvalues = new Object[0][colnames.length];

    if (inputfiles != null) {
        rowvalues = new Object[inputfiles.length][colnames.length];
        for (int i = 0; i < inputfiles.length; ++i) {

            rowvalues[i][0] = inputfiles[i].getName();
        }
    }

    table = new JTable(rowvalues, colnames);

    table.setFillsViewportHeight(true);

    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    table.isOpaque();
    int size = 100;
    table.getColumnModel().getColumn(0).setPreferredWidth(size);
    table.getColumnModel().getColumn(1).setPreferredWidth(size);
    table.getColumnModel().getColumn(2).setPreferredWidth(size);
    table.getColumnModel().getColumn(3).setPreferredWidth(size);
    table.getColumnModel().getColumn(4).setPreferredWidth(size);
    table.getColumnModel().getColumn(5).setPreferredWidth(size);
    table.getColumnModel().getColumn(6).setPreferredWidth(size);
    table.getColumnModel().getColumn(7).setPreferredWidth(size);
    maxErrorField = new TextField(5);
    maxErrorField.setText(Float.toString(maxError));

    minInlierField = new TextField(5);
    minInlierField.setText(Float.toString(minInliers));

    maxGapField = new TextField(5);
    maxGapField.setText(Float.toString(maxDist));

    maxSlopeField = new TextField(5);
    maxSlopeField.setText(Float.toString(maxSlope));

    minSlopeField = new TextField(5);
    minSlopeField.setText(Float.toString(minSlope));

    maxErrorSB.setSize(new Dimension(SizeX, 20));
    minSlopeSB.setSize(new Dimension(SizeX, 20));
    minInliersSB.setSize(new Dimension(SizeX, 20));
    maxDistSB.setSize(new Dimension(SizeX, 20));
    maxSlopeSB.setSize(new Dimension(SizeX, 20));
    maxErrorField.setSize(new Dimension(SizeX, 20));
    minInlierField.setSize(new Dimension(SizeX, 20));
    maxGapField.setSize(new Dimension(SizeX, 20));
    minSlopeField.setSize(new Dimension(SizeX, 20));
    maxSlopeField.setSize(new Dimension(SizeX, 20));

    scrollPane = new JScrollPane(table);
    scrollPane.setMinimumSize(new Dimension(300, 200));
    scrollPane.setPreferredSize(new Dimension(300, 200));

    scrollPane.getViewport().add(table);
    scrollPane.setAutoscrolls(true);

    // Location
    panelFirst.setLayout(layout);
    panelSecond.setLayout(layout);
    PanelSavetoFile.setLayout(layout);
    PanelParameteroptions.setLayout(layout);
    Panelfunction.setLayout(layout);
    Panelslope.setLayout(layout);
    PanelCompileRes.setLayout(layout);
    PanelDirectory.setLayout(layout);

    panelCont.setLayout(cl);

    panelCont.add(panelFirst, "1");
    panelCont.add(panelSecond, "2");

    panelFirst.setName("Ransac fits for rates and frequency analysis");
    c.insets = new Insets(5, 5, 5, 5);
    c.anchor = GridBagConstraints.BOTH;
    c.ipadx = 35;

    inputLabelT = new Label("Compute length distribution at time: ");
    inputLabelTcont = new Label("(Press Enter to start computation) ");
    inputFieldT = new TextField(5);
    inputFieldT.setText("1");

    c.gridwidth = 10;
    c.gridheight = 10;
    c.gridy = 1;
    c.gridx = 0;

    String[] Method = { "Linear Function only", "Linearized Quadratic function", "Linearized Cubic function" };
    JComboBox<String> ChooseMethod = new JComboBox<String>(Method);

    final Checkbox findCatastrophe = new Checkbox("Detect Catastrophies", this.detectCatastrophe);
    final Checkbox findmanualCatastrophe = new Checkbox("Detect Catastrophies without fit",
            this.detectmanualCatastrophe);
    final Scrollbar minCatDist = new Scrollbar(Scrollbar.HORIZONTAL, this.minDistCatInt, 1, MIN_SLIDER,
            MAX_SLIDER + 1);
    final Scrollbar maxRes = new Scrollbar(Scrollbar.HORIZONTAL, this.restoleranceInt, 1, MIN_SLIDER,
            MAX_SLIDER + 1);
    final Label minCatDistLabel = new Label("Min. Catastrophy height (tp) = " + this.minDistanceCatastrophe,
            Label.CENTER);
    final Button done = new Button("Done");
    final Button batch = new Button("Save Parameters for Batch run");
    final Button cancel = new Button("Cancel");
    final Button Compile = new Button("Compute rates and freq. till current file");
    final Button AutoCompile = new Button("Auto Compute Velocity and Frequencies");
    final Button Measureserial = new Button("Select directory of MTrack generated files");
    final Button WriteLength = new Button("Compute length distribution at framenumber : ");
    final Button WriteStats = new Button("Compute lifetime and mean length distribution");
    final Button WriteAgain = new Button("Save Velocity and Frequencies to File");

    PanelDirectory.add(Measureserial, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelDirectory.add(scrollPane, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    PanelDirectory.setBorder(selectdirectory);
    PanelDirectory.setPreferredSize(new Dimension(SizeX, SizeY));
    panelFirst.add(PanelDirectory, new GridBagConstraints(0, 0, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combomaxerror = new SliderBoxGUI(errorstring, maxErrorSB, maxErrorField, maxErrorLabel,
            scrollbarSize, maxError, MAX_ERROR);

    PanelParameteroptions.add(combomaxerror.BuildDisplay(), new GridBagConstraints(0, 0, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combomininlier = new SliderBoxGUI(inlierstring, minInliersSB, minInlierField, minInliersLabel,
            scrollbarSize, minInliers, MAX_Inlier);

    PanelParameteroptions.add(combomininlier.BuildDisplay(), new GridBagConstraints(0, 2, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combomaxdist = new SliderBoxGUI(maxgapstring, maxDistSB, maxGapField, maxDistLabel,
            scrollbarSize, maxDist, MAX_Gap);

    PanelParameteroptions.add(combomaxdist.BuildDisplay(), new GridBagConstraints(0, 3, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelParameteroptions.add(ChooseMethod, new GridBagConstraints(0, 4, 3, 1, 0.0, 0.0,
            GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelParameteroptions.add(lambdaSB, new GridBagConstraints(0, 5, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    PanelParameteroptions.add(lambdaLabel, new GridBagConstraints(0, 6, 3, 1, 0.0, 0.0,
            GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelParameteroptions.setPreferredSize(new Dimension(SizeX, SizeY));
    PanelParameteroptions.setBorder(selectparam);
    panelFirst.add(PanelParameteroptions, new GridBagConstraints(3, 0, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combominslope = new SliderBoxGUI(minslopestring, minSlopeSB, minSlopeField, minSlopeLabel,
            scrollbarSize, (float) minSlope, (float) MAX_ABS_SLOPE);

    Panelslope.add(combominslope.BuildDisplay(), new GridBagConstraints(0, 0, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combomaxslope = new SliderBoxGUI(maxslopestring, maxSlopeSB, maxSlopeField, maxSlopeLabel,
            scrollbarSize, (float) maxSlope, (float) MAX_ABS_SLOPE);

    Panelslope.add(combomaxslope.BuildDisplay(), new GridBagConstraints(0, 2, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    Panelslope.add(findCatastrophe, new GridBagConstraints(0, 4, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    Panelslope.add(findmanualCatastrophe, new GridBagConstraints(4, 4, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    Panelslope.add(minCatDist, new GridBagConstraints(0, 5, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    Panelslope.add(minCatDistLabel, new GridBagConstraints(0, 6, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    Panelslope.setBorder(selectslope);
    Panelslope.setPreferredSize(new Dimension(SizeX, SizeY));

    panelFirst.add(Panelslope, new GridBagConstraints(3, 1, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.add(AutoCompile, new GridBagConstraints(0, 0, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.add(WriteLength, new GridBagConstraints(0, 1, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.add(inputFieldT, new GridBagConstraints(3, 1, 3, 1, 0.1, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.add(WriteStats, new GridBagConstraints(0, 4, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.setPreferredSize(new Dimension(SizeX, SizeY));

    PanelCompileRes.setBorder(compileres);

    panelFirst.add(PanelCompileRes, new GridBagConstraints(0, 1, 3, 1, 0.0, 0.0, GridBagConstraints.EAST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    if (inputfiles != null) {

        table.addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() >= 1) {

                    if (!jFreeChartFrame.isVisible())
                        jFreeChartFrame = Tracking.display(chart, new Dimension(500, 500));
                    JTable target = (JTable) e.getSource();
                    row = target.getSelectedRow();
                    // do some action if appropriate column
                    if (row > 0)
                        displayclicked(row);
                    else
                        displayclicked(0);
                }
            }
        });
    }

    maxErrorSB.addAdjustmentListener(new ErrorListener(this, maxErrorLabel, errorstring, MIN_ERROR, MAX_ERROR,
            scrollbarSize, maxErrorSB));

    minInliersSB.addAdjustmentListener(new MinInlierListener(this, minInliersLabel, inlierstring, MIN_Inlier,
            MAX_Inlier, scrollbarSize, minInliersSB));

    maxDistSB.addAdjustmentListener(
            new MaxDistListener(this, maxDistLabel, maxgapstring, MIN_Gap, MAX_Gap, scrollbarSize, maxDistSB));

    ChooseMethod.addActionListener(new FunctionItemListener(this, ChooseMethod));
    lambdaSB.addAdjustmentListener(new LambdaListener(this, lambdaLabel, lambdaSB));
    minSlopeSB.addAdjustmentListener(new MinSlopeListener(this, minSlopeLabel, minslopestring,
            (float) MIN_ABS_SLOPE, (float) MAX_ABS_SLOPE, scrollbarSize, minSlopeSB));

    maxSlopeSB.addAdjustmentListener(new MaxSlopeListener(this, maxSlopeLabel, maxslopestring,
            (float) MIN_ABS_SLOPE, (float) MAX_ABS_SLOPE, scrollbarSize, maxSlopeSB));
    findCatastrophe.addItemListener(
            new CatastrophyCheckBoxListener(this, findCatastrophe, minCatDistLabel, minCatDist));
    findmanualCatastrophe.addItemListener(
            new ManualCatastrophyCheckBoxListener(this, findmanualCatastrophe, minCatDistLabel, minCatDist));
    minCatDist.addAdjustmentListener(new MinCatastrophyDistanceListener(this, minCatDistLabel, minCatDist));
    Measureserial.addActionListener(new MeasureserialListener(this));
    Compile.addActionListener(new CompileResultsListener(this));
    AutoCompile.addActionListener(new AutoCompileResultsListener(this));
    WriteLength.addActionListener(new WriteLengthListener(this));
    WriteStats.addActionListener(new WriteStatsListener(this));
    WriteAgain.addActionListener(new WriteRatesListener(this));
    done.addActionListener(new FinishButtonListener(this, false));
    batch.addActionListener(new RansacBatchmodeListener(this));
    cancel.addActionListener(new FinishButtonListener(this, true));
    inputFieldT.addTextListener(new LengthdistroListener(this));

    maxSlopeField.addTextListener(new MaxSlopeLocListener(this, false));
    minSlopeField.addTextListener(new MinSlopeLocListener(this, false));
    maxErrorField.addTextListener(new ErrorLocListener(this, false));
    minInlierField.addTextListener(new MinInlierLocListener(this, false));
    maxGapField.addTextListener(new MaxDistLocListener(this, false));

    panelFirst.setVisible(true);
    functionChoice = 0;

    cl.show(panelCont, "1");

    Cardframe.add(panelCont, BorderLayout.CENTER);

    setFunction();
    Cardframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    Cardframe.pack();
    Cardframe.setVisible(true);
    Cardframe.pack();

}

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Set the tab and return behavior for a table.
 *///from  w w  w.ja  v  a  2  s.c om
private void setupTabReturnBehavior(final JTable table) {
    final InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

    // Have the enter key work the same as the tab key
    final KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    final KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    im.put(enter, im.get(tab));

    // Override the default tab behavior
    // Tab to the next editable cell. When no editable cells goto next cell.
    final Action oldTabAction = table.getActionMap().get(im.get(tab));
    final Action tabAction = new AbstractAction() {
        public void actionPerformed(final ActionEvent e) {
            if (null != oldTabAction) {
                oldTabAction.actionPerformed(e);
            }

            final JTable table = (JTable) e.getSource();
            final int rowCount = table.getRowCount();
            final int columnCount = table.getColumnCount();
            int row = table.getSelectedRow();
            int column = table.getSelectedColumn();

            // skip the no show when tabbing
            while (!table.isCellEditable(row, column) || table.getColumnClass(column) == Boolean.class) {
                column += 1;

                if (column == columnCount) {
                    column = 0;
                    row += 1;
                }

                if (row == rowCount) {
                    row = 0;
                }

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

            table.changeSelection(row, column, false, false);
        }
    };
    table.getActionMap().put(im.get(tab), tabAction);
}

From source file:de.wusel.partyplayer.gui.PartyPlayer.java

private Component createSongPanel() {
    final SongsTableModel model = new SongsTableModel(playerModel, settings, this);

    table = new JXTable(model) {

        @Override//w w  w .  j  a va 2s  .com
        public String getToolTipText(MouseEvent event) {
            int viewRowIndex = rowAtPoint(event.getPoint());
            if (viewRowIndex != -1) {
                int modelIndex = convertRowIndexToModel(viewRowIndex);
                SongWrapper songFromList = playerModel.getSongFromList(modelIndex);
                return songFromList.getFileName();
            }
            return super.getToolTipText(event);
        }
    };

    table.setAutoCreateRowSorter(true);
    String numberColumnName = getText("table.songs.column.number.label");
    table.getColumn(numberColumnName).setMaxWidth(25);
    table.getColumn(numberColumnName).setResizable(false);
    TableSortController sorter = (TableSortController) table.getRowSorter();
    sorter.setComparator(2, new SongComparator());

    table.getColumn(numberColumnName).setCellRenderer(new SubstanceDefaultTableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);
            if (value != null)
                label.setText(((SongWrapper) value).getTrackNumber() + "");
            return label;
        }
    });

    table.getColumn(getText("table.songs.column.duration.label"))
            .setCellRenderer(new SubstanceDefaultTableCellRenderer() {

                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                    JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected,
                            hasFocus, row, column);
                    if (value != null)
                        label.setText(Util.getTimeString((Double) value));
                    return label;
                }
            });

    table.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                addSongToPlaylist(
                        playerModel.getSongFromList(table.convertRowIndexToModel(table.getSelectedRow())));
            }
        }
    });

    table.addKeyListener(new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                addSongToPlaylist(
                        playerModel.getSongFromList(table.convertRowIndexToModel(table.getSelectedRow())));
            }
        }
    });

    JScrollPane scrollPane = new JScrollPane(table);
    table.setFillsViewportHeight(true);
    return scrollPane;
}

From source file:com.itemanalysis.jmetrik.gui.Jmetrik.java

public Jmetrik() {
    super("jMetrik");
    setPreferredSize(new Dimension(1024, 650));
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    //properly close database if user closes window
    this.addWindowListener(new WindowAdapter() {
        @Override/*w ww .j a v a  2  s  .  c  om*/
        public void windowClosing(WindowEvent we) {
            if (workspace != null) {
                workspace.closeDatabase();
            }
            System.exit(0);
        }
    });

    //add statusbar
    statusBar = new StatusBar(1024, 30);
    statusBar.setBorder(new EmptyBorder(2, 2, 2, 2));
    getContentPane().add(statusBar, BorderLayout.SOUTH);

    //start logging
    startLog();

    //left-right splitpane
    JSplitPane splitPane1 = new JSplitPane();
    splitPane1.setDividerLocation(200);

    //setup workspace list
    workspaceList = new JList();
    workspaceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    workspaceList.setModel(new SortedListModel<DataTableName>());
    workspaceList.addKeyListener(new DeleteKeyListener());
    //        workspaceList.getInsets().set(5, 5, 5, 5);

    //add icon to list cell renderer
    String urlString = "/images/spreadsheet.png";
    URL url = this.getClass().getResource(urlString);
    final ImageIcon tableIcon = new ImageIcon(url, "Table");
    workspaceList.setCellRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,
                    cellHasFocus);
            label.setIcon(tableIcon);
            return label;
        }
    });

    JScrollPane scrollPane1 = new JScrollPane(workspaceList);
    scrollPane1.setPreferredSize(new Dimension(200, 698));

    splitPane1.setLeftComponent(scrollPane1);

    //tabbed pane for top pane
    tabbedPane = new JTabbedPane();
    tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);

    //setup data table
    dataTable = new DataTable();
    dataTable.setRowHeight(18);

    //change size of table header and center text
    JTableHeader header = dataTable.getTableHeader();
    header.setDefaultRenderer(new TableHeaderCellRenderer());

    JScrollPane dataScrollPane = new JScrollPane(dataTable);
    tabbedPane.addTab("Data", dataScrollPane);

    //setup variable table
    variableTable = new DataTable();
    variableTable.setRowHeight(18);
    variableTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);
            if (e.getClickCount() == 2) {
                JTable target = (JTable) e.getSource();
                int row = target.getSelectedRow();
                int col = target.getSelectedColumn();
                if (col == 0) {
                    if (target.getModel() instanceof VariableModel) {
                        VariableModel vModel = (VariableModel) target.getModel();
                        String s = (String) vModel.getValueAt(row, col);

                        DatabaseName db = workspace.getDatabaseName();
                        DataTableName table = workspace.getCurrentDataTable();

                        RenameVariableDialog renameVariableDialog = new RenameVariableDialog(Jmetrik.this, db,
                                table, s);
                        renameVariableDialog.setVisible(true);

                        if (renameVariableDialog.canRun()) {
                            RenameVariableCommand command = renameVariableDialog.getCommand();
                            workspace.runProcess(command);
                        }

                    } //end instanceof

                } //end if col==0

            } //end if click count==2
        }//end mouse clicked
    });

    //change size of table header and center text
    JTableHeader variableHeader = variableTable.getTableHeader();
    variableHeader.setDefaultRenderer(new TableHeaderCellRenderer());
    variableHeader.setPreferredSize(new Dimension(30, 21));

    JScrollPane variableScrollPane = new JScrollPane(variableTable);
    tabbedPane.addTab("Variables", variableScrollPane);

    splitPane1.setRightComponent(tabbedPane);
    getContentPane().add(splitPane1, BorderLayout.CENTER);

    //add status bar listener - needed to display status message that are generated within this class
    this.addPropertyChangeListener(statusBar.getStatusListener());

    //add listener for displaying error messages - needed to display errors and exceptions
    this.addPropertyChangeListener(new ErrorOccurredPropertyChangeListener());

    //instantiate file utilities
    fileUtils = new JmetrikFileUtils();
    fileUtils.addPropertyChangeListener(statusBar.getStatusListener());

    //set import and export path to user's documents folder
    JFileChooser chooser = new JFileChooser();
    FileSystemView fw = chooser.getFileSystemView();
    importExportPath = fw.getDefaultDirectory().toString().replaceAll("\\\\", "/");

    //create and start a workspace
    startWorkspace();

    //create menu bar and tool bar
    this.setJMenuBar(createMenuBar());

    JToolBar toolBar = createToolBar();
    toolBar.setFloatable(false);
    toolBar.setRollover(true);
    getContentPane().add(toolBar, BorderLayout.PAGE_START);

    pack();

}