Example usage for javax.swing JTable setRowSelectionInterval

List of usage examples for javax.swing JTable setRowSelectionInterval

Introduction

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

Prototype

public void setRowSelectionInterval(int index0, int index1) 

Source Link

Document

Selects the rows from index0 to index1, inclusive.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);

    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    table.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(false);

    table.setColumnSelectionAllowed(false);
    table.setRowSelectionAllowed(true);//w  ww.  ja v a  2s. co m

    table.setRowSelectionInterval(0, 0);
}

From source file:MainClass.java

public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
        int column) {
    if (value == null) {
        return this;
    }//  ww  w .j  ava 2  s .c  o m
    if (value instanceof Volume) {
        setValue(((Volume) value).getVolume());
    } else {
        setValue(0);
    }
    table.setRowSelectionInterval(row, row);
    table.setColumnSelectionInterval(column, column);
    originalValue = getValue();
    editing = true;
    Point p = table.getLocationOnScreen();
    Rectangle r = table.getCellRect(row, column, true);
    helper.setLocation(r.x + p.x + getWidth() - 50, r.y + p.y + getHeight());
    helper.setVisible(true);
    return this;
}

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

/**
 * New Zip file chooser./*from  www.  j a va  2s .  com*/
 *
 * @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:me.mayo.telnetkek.MainPanel.java

public final void setupTablePopup() {
    this.tblPlayers.addMouseListener(new MouseAdapter() {
        @Override//  w  ww.j  a  va2s.  co 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: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);/*  www. j  a  v a2  s  .  co m*/
    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:marytts.tools.redstart.AdminWindow.java

private void buildPromptTable() {

    this.promptArray = this.currentSession.getPromptArray();

    System.out.println("Loading prompts...");
    Test.output("Array contains " + promptArray.length + " prompts.");

    // Make column names array
    String[] columnNames = new String[3];
    columnNames[REC_STATUS_COLUMN] = "Status";
    columnNames[BASENAME_COLUMN] = "Basename";
    columnNames[PROMPT_TEXT_COLUMN] = "Prompt Preview";

    // Now create the table itself        
    JTable table = new JTable(new PromptTableModel(promptArray, columnNames, redAlertMode));
    table.setColumnSelectionAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // Set alignment for the status colum to centered
    DefaultTableCellRenderer renderer = new ClippingColorRenderer();
    renderer.setHorizontalAlignment(JTextField.CENTER);
    table.getColumnModel().getColumn(REC_STATUS_COLUMN).setCellRenderer(renderer);

    // Set selection highlight colour to light blue
    table.setSelectionBackground(new java.awt.Color(153, 204, 255));

    // Add listeners
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent evt) {
            displayPromptText();// w ww . j av a  2s .  co  m
        }
    });

    // Store the table in an instance field accessible to the entire class
    this.jTable_PromptSet = table;

    Thread recordingStatusInitialiser = new Thread() {
        public void run() {
            updateAllRecStatus();
        }
    };
    recordingStatusInitialiser.start();

    // Display table in the appropriate component pane
    jScrollPane_PromptSet.setViewportView(table);

    if (promptArray.length > 0) {
        table.setRowSelectionInterval(0, 0); // Show first row of prompt table as selected               
        displayPromptText(); // Display the prompt text for the first prompt in the prompt display pane 
    }
    setColumnWidths();

    System.out.println("Total " + table.getRowCount() + " prompts loaded.");

}

From source file:jp.massbank.spectrumsearch.SearchPage.java

/**
 * ??/*from   www.j av  a  2 s  .  c  om*/
 */
private void updateSelectQueryTable(JTable tbl) {

    // ?
    this.setCursor(waitCursor);

    int selRow = tbl.getSelectedRow();
    if (selRow >= 0) {
        tbl.clearSelection();
        Color defColor = tbl.getSelectionBackground();
        tbl.setRowSelectionInterval(selRow, selRow);
        tbl.setSelectionBackground(Color.PINK);
        tbl.update(tbl.getGraphics());
        tbl.setSelectionBackground(defColor);
    }
    // ?
    this.setCursor(Cursor.getDefaultCursor());
}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositMain.java

private void jobQueueMousePressedCommon(java.awt.event.MouseEvent evt, JTable table) {
    if (evt.isPopupTrigger()) {
        if (table.getSelectedRowCount() == 0) {
            int row = table.rowAtPoint(evt.getPoint());
            if (row > -1) {
                table.setRowSelectionInterval(row, row);
            }//ww w.  j a  v  a 2  s .co m
        }
        JPopupMenu menu = depositPresenter.getJobQueueMenu((JTable) evt.getSource());
        if (menu != null) {
            menu.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }
}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositMain.java

private void jobQueueMouseReleaseCommon(java.awt.event.MouseEvent evt, JTable table) {
    if (evt.isPopupTrigger()) {
        if (table.getSelectedRowCount() == 0) {
            int row = table.rowAtPoint(evt.getPoint());
            if (row > -1) {
                table.setRowSelectionInterval(row, row);
            }//from   ww w . j a  v a  2 s . com
        }
        JPopupMenu menu = depositPresenter.getJobQueueMenu((JTable) evt.getSource());
        if (menu != null) {
            menu.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }
}

From source file:org.formic.wizard.step.gui.FeatureListStep.java

/**
 * {@inheritDoc}// w  w w .  ja  v a 2 s . c om
 * @see org.formic.wizard.step.GuiStep#init()
 */
public Component init() {
    featureInfo = new JEditorPane("text/html", StringUtils.EMPTY);
    featureInfo.setEditable(false);
    featureInfo.addHyperlinkListener(new HyperlinkListener());

    Feature[] features = provider.getFeatures();
    JTable table = new JTable(features.length, 1) {
        private static final long serialVersionUID = 1L;

        public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }

        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    table.setBackground(new javax.swing.JList().getBackground());

    GuiForm form = createForm();

    for (int ii = 0; ii < features.length; ii++) {
        final Feature feature = (Feature) features[ii];
        final JCheckBox box = new JCheckBox();

        String name = getName() + '.' + feature.getKey();
        form.bind(name, box);

        box.putClientProperty("feature", feature);
        featureMap.put(feature.getKey(), box);

        if (feature.getInfo() == null) {
            feature.setInfo(Installer.getString(getName() + "." + feature.getKey() + ".html"));
        }
        feature.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
                if (Feature.ENABLED_PROPERTY.equals(event.getPropertyName())) {
                    if (box.isSelected() != feature.isEnabled()) {
                        box.setSelected(feature.isEnabled());
                    }
                }
            }
        });

        box.setText(Installer.getString(name));
        box.setBackground(table.getBackground());
        if (!feature.isAvailable()) {
            box.setSelected(false);
            box.setEnabled(false);
        }
        table.setValueAt(box, ii, 0);
    }

    FeatureListMouseListener mouseListener = new FeatureListMouseListener();
    for (int ii = 0; ii < features.length; ii++) {
        Feature feature = (Feature) features[ii];
        if (feature.isEnabled() && feature.isAvailable()) {
            JCheckBox box = (JCheckBox) featureMap.get(feature.getKey());
            box.setSelected(true);
            mouseListener.processDependencies(feature);
            mouseListener.processExclusives(feature);
        }
    }

    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowHorizontalLines(false);
    table.setShowVerticalLines(false);
    table.setDefaultRenderer(JCheckBox.class, new ComponentTableCellRenderer());

    table.addKeyListener(new FeatureListKeyListener());
    table.addMouseListener(mouseListener);
    table.getSelectionModel().addListSelectionListener(new FeatureListSelectionListener(table));

    table.setRowSelectionInterval(0, 0);

    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    JPanel container = new JPanel(new BorderLayout());
    container.add(table, BorderLayout.CENTER);
    panel.add(new JScrollPane(container), BorderLayout.CENTER);
    JScrollPane infoScroll = new JScrollPane(featureInfo);
    infoScroll.setMinimumSize(new Dimension(0, 50));
    infoScroll.setMaximumSize(new Dimension(0, 50));
    infoScroll.setPreferredSize(new Dimension(0, 50));
    panel.add(infoScroll, BorderLayout.SOUTH);

    return panel;
}