Example usage for javax.swing JTable clearSelection

List of usage examples for javax.swing JTable clearSelection

Introduction

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

Prototype

public void clearSelection() 

Source Link

Document

Deselects all selected columns and rows.

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.clearSelection();
}

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

public final void setupTablePopup() {
    this.tblPlayers.addMouseListener(new MouseAdapter() {
        @Override/*  w w w. jav a  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:jp.massbank.spectrumsearch.SearchPage.java

/**
 * ??//from  w  w w .  ja  v  a 2  s.  c  o m
 */
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:nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.java

private void testClickInTable(boolean firstStarred, boolean firstRead, boolean spanTable, boolean selectRow,
        int xMouseEvent) throws InterruptedException, InvocationTargetException {
    List<Article> testArticles = TestUtilities.getSixTestArticles();
    testArticles.get(0).setStarred(firstStarred);
    testArticles.get(0).setRead(firstRead);

    MainGui mainGui = new MainGui(mockManyBrowsersPanel);
    mainGui.setMainCallbacks(mockMainCallbacks);

    Mockito.when(mockConfiguration.useSpanTable()).thenReturn(spanTable);

    mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
    mainGui.initializeGui(testArticles);

    waitForGuiTasks();/* ww w  .j  a v a  2s  .  c om*/

    JTable table = (JTable) findComponent(mockContentPane, JTable.class);
    assertNotNull(table);

    if (selectRow) {
        table.getSelectionModel().setValueIsAdjusting(true);
        table.getSelectionModel().setSelectionInterval(1, 1);
        table.getSelectionModel().setValueIsAdjusting(true);
        table.getSelectionModel().setSelectionInterval(0, 0);
    } else {
        table.getSelectionModel().setValueIsAdjusting(true);
        table.clearSelection();
    }

    MouseEvent mouseEvent = new MouseEvent(table, 123456, new Date().getTime(), 0, xMouseEvent, 10, 1, false);

    for (MouseListener mouseListener : table.getMouseListeners()) {
        mouseListener.mouseClicked(mouseEvent);
    }
}

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

/**
 * @deprecated Move to ResultController hierarchy.
 *//*from w  w  w  . j av  a 2  s .com*/
private void cmdRestoreCurrentCollectableInDetails() {
    assert getCollectStateModel().getCollectState()
            .equals(new CollectState(CollectState.OUTERSTATE_DETAILS, CollectState.DETAILSMODE_VIEW));

    if (stopEditingInDetails()) {
        final String sMessage = getSpringLocaleDelegate().getMessage("GenericObjectCollectController.75",
                "Soll der angezeigte Datensatz ({0}) wirklich wiederhergestellt werden?",
                getSelectedCollectable().getIdentifierLabel());
        final int iBtn = JOptionPane.showConfirmDialog(getTab(), sMessage, getSpringLocaleDelegate().getMessage(
                "GenericObjectCollectController.28", "Datensatz wiederherstellen"), JOptionPane.YES_NO_OPTION);

        if (iBtn == JOptionPane.OK_OPTION)
            UIUtils.runCommand(getTab(), new Runnable() {
                @Override
                public void run() {
                    try {
                        // try to find next or previous object:
                        final JTable tblResult = getResultTable();
                        final int iSelectedRow = tblResult.getSelectedRow();
                        if (iSelectedRow < 0)
                            throw new IllegalStateException();

                        final int iNewSelectedRow;
                        if (iSelectedRow < tblResult.getRowCount() - 1)
                            // the selected row is not the last row: select the next row
                            iNewSelectedRow = iSelectedRow;
                        else if (iSelectedRow > 0)
                            // the selected row is not the first row: select the previous row
                            iNewSelectedRow = iSelectedRow - 1;
                        else {
                            // the selected row is the single row: don't select a row
                            assert tblResult.getRowCount() == 1;
                            assert iSelectedRow == 0;
                            iNewSelectedRow = -1;
                        }

                        checkedRestoreCollectable(getSelectedCollectable());
                        getResultTableModel().remove(getSelectedCollectable());
                        getSearchStrategy().search(true);

                        if (iNewSelectedRow == -1) {
                            tblResult.clearSelection();
                            // switch to new mode:
                            getResultController().getSearchResultStrategy().refreshResult();
                        } else {
                            tblResult.setRowSelectionInterval(iNewSelectedRow, iNewSelectedRow);
                            // go into view mode again:
                            cmdEnterViewMode();
                        }
                    } catch (CommonPermissionException ex) {
                        final String sErrorMessage = getSpringLocaleDelegate().getMessage(
                                "GenericObjectCollectController.67",
                                "Sie verf\u00fcgen nicht \u00fcber die ausreichenden Rechte, um diesen Datensatz wiederherzustellen.");
                        Errors.getInstance().showExceptionDialog(getTab(), sErrorMessage, ex);
                    } catch (CommonBusinessException ex) {
                        Errors.getInstance().showExceptionDialog(getTab(),
                                getSpringLocaleDelegate().getMessage("GenericObjectCollectController.33",
                                        "Der Datensatz konnte nicht wiederhergestellt werden."),
                                ex);
                    }
                }
            });
    }
    setDeleteButtonToggleInDetails();
}

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

/**
 * Delete the selected object physically.
 * This is mostly a copy from CollectController.cmdDelete; just the message and the called delete method are different.
 *///from  w  ww .  j a v  a2  s. com
protected void cmdDeletePhysically() {
    assert getCollectStateModel().getCollectState()
            .equals(new CollectState(CollectState.OUTERSTATE_DETAILS, CollectState.DETAILSMODE_VIEW));

    if (stopEditingInDetails()) {
        final String sMessage = getSpringLocaleDelegate().getMessage("GenericObjectCollectController.73",
                "Soll der angezeigte Datensatz ({0}) wirklich endg\u00fcltig aus der Datenbank gel\u00f6scht werden?\nDieser Vorgang kann nicht r\u00fcckg\u00e4ngig gemacht werden! ",
                getSelectedCollectable().getIdentifierLabel());
        final int iBtn = JOptionPane.showConfirmDialog(getTab(), sMessage, getSpringLocaleDelegate()
                .getMessage("GenericObjectCollectController.24", "Datensatz endg\u00fcltig l\u00f6schen"),
                JOptionPane.YES_NO_OPTION);

        if (iBtn == JOptionPane.OK_OPTION)
            UIUtils.runCommand(getTab(), new Runnable() {
                @Override
                public void run() {
                    try {
                        // try to find next or previous object:
                        final JTable tblResult = getResultTable();
                        final int iSelectedRow = tblResult.getSelectedRow();
                        if (iSelectedRow < 0)
                            throw new IllegalStateException();

                        final int iNewSelectedRow;
                        if (iSelectedRow < tblResult.getRowCount() - 1)
                            // the selected row is not the last row: select the next row
                            iNewSelectedRow = iSelectedRow;
                        else if (iSelectedRow > 0)
                            // the selected row is not the first row: select the previous row
                            iNewSelectedRow = iSelectedRow - 1;
                        else {
                            // the selected row is the single row: don't select a row
                            assert tblResult.getRowCount() == 1;
                            assert iSelectedRow == 0;
                            iNewSelectedRow = -1;
                        }

                        checkedDeleteCollectablePhysically(getSelectedCollectable());

                        if (iNewSelectedRow == -1) {
                            tblResult.clearSelection();
                            // switch to new mode:
                            setCollectState(CollectState.OUTERSTATE_DETAILS, CollectState.DETAILSMODE_NEW);
                        } else {
                            tblResult.setRowSelectionInterval(iNewSelectedRow, iNewSelectedRow);
                            // go into view mode again:
                            setCollectState(CollectState.OUTERSTATE_DETAILS, CollectState.DETAILSMODE_VIEW);
                        }
                    } catch (CommonPermissionException ex) {
                        final String sErrorMessage = getSpringLocaleDelegate().getMessage(
                                "GenericObjectCollectController.70",
                                "Sie verf\u00fcgen nicht \u00fcber die ausreichenden Rechte, um dieses Objekt zu l\u00f6schen.");
                        Errors.getInstance().showExceptionDialog(getTab(), sErrorMessage, ex);
                    } catch (CommonBusinessException ex) {
                        if (!handlePointerException(ex))
                            Errors.getInstance().showExceptionDialog(getTab(),
                                    getSpringLocaleDelegate().getMessage("GenericObjectCollectController.18",
                                            "Das Objekt konnte nicht gel\u00f6scht werden."),
                                    ex);
                    }
                }
            });
    }
}

From source file:org.rdv.datapanel.DigitalTabularDataPanel.java

/**
 * Remove all the rows in the specified table that are selected. If a
 * selected row is not blank, the channel in that row will be removed.
 * /*ww  w .ja va2  s.  c  o  m*/
 * @param tableIndex
 *            the index of the table
 */
private void removeSelectedRows(int tableIndex) {
    List<String> selectedChannels = new ArrayList<String>();

    JTable table = tables.get(tableIndex);
    int[] selectedRows = table.getSelectedRows();
    table.clearSelection();

    DataTableModel tableModel = tableModels.get(tableIndex);
    for (int j = selectedRows.length - 1; j >= 0; j--) {
        int row = selectedRows[j];
        if (tableModel.isBlankRow(row)) {
            tableModel.deleteBlankRow(row);
        } else {
            DataRow dataRow = tableModel.getRowAt(row);
            selectedChannels.add(dataRow.getName());
        }
    }

    for (String channelName : selectedChannels) {
        removeChannel(channelName);
    }
}

From source file:pl.otros.logview.api.gui.LogViewPanelWrapper.java

private void addRowAutoScroll() {
    dataTableModel.addTableModelListener(e -> {
        if (follow.isSelected() && e.getType() == TableModelEvent.INSERT) {
            final Runnable r = () -> {
                try {
                    JTable table = logViewPanel.getTable();
                    int row = table.getRowCount() - 1;
                    if (row > 0) {
                        Rectangle rect = table.getCellRect(row, 0, true);
                        table.scrollRectToVisible(rect);
                        table.clearSelection();
                        table.setRowSelectionInterval(row, row);
                    }//from   w w  w .j  av a  2 s . c  o  m
                } catch (IllegalArgumentException iae) {
                    // ignore..out of bounds
                    iae.printStackTrace();
                }
            };
            // Wait for JViewPort size update
            // TODO Find way to invoke this listener after viewport is notified about changes
            Runnable r2 = () -> {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException ignore) {
                }
                SwingUtilities.invokeLater(r);
            };
            new Thread(r2).start();
        }
    });
}

From source file:pl.otros.logview.gui.actions.search.SearchAction.java

public void performSearch(String text, SearchDirection direction) {
    StatusObserver statusObserver = getOtrosApplication().getStatusObserver();
    JTabbedPane jTabbedPane = getOtrosApplication().getJTabbedPane();
    LogViewPanelWrapper lvPanel = (LogViewPanelWrapper) jTabbedPane.getSelectedComponent();
    if (lvPanel == null) {
        return;//from   w ww.  ja v  a  2s  .c o m
    }
    JTable table = lvPanel.getLogViewPanel().getTable();

    NextRowProvider nextRowProvider = NextRowProviderFactory.getFilteredTableRow(table, direction);
    SearchContext context = new SearchContext();
    context.setDataTableModel(lvPanel.getDataTableModel());
    SearchMatcher searchMatcher = null;
    String confKey = null;
    if (SearchMode.STRING_CONTAINS.equals(searchMode)) {
        searchMatcher = new StringContainsSearchMatcher(text);
        confKey = ConfKeys.SEARCH_LAST_STRING;
    } else if (SearchMode.REGEX.equals(searchMode)) {
        try {
            searchMatcher = new RegexMatcher(text);
            confKey = ConfKeys.SEARCH_LAST_REGEX;
        } catch (Exception e) {
            statusObserver.updateStatus("Error in regular expression: " + e.getMessage(),
                    StatusObserver.LEVEL_ERROR);
            return;
        }
    } else if (SearchMode.QUERY.equals(searchMode)) {
        QueryAcceptCondition acceptCondition;
        try {
            acceptCondition = new QueryAcceptCondition(text);
            searchMatcher = new AcceptConditionSearchMatcher(acceptCondition);
            confKey = ConfKeys.SEARCH_LAST_QUERY;
        } catch (RuleException e) {
            statusObserver.updateStatus("Wrong query rule: " + e.getMessage(), StatusObserver.LEVEL_ERROR);
            return;

        }
    }
    updateList(confKey, getOtrosApplication().getConfiguration(), text);
    DefaultComboBoxModel model = (DefaultComboBoxModel) getOtrosApplication().getSearchField().getModel();
    model.removeElement(text);
    model.insertElementAt(text, 0);
    model.setSelectedItem(text);
    int maxCount = getOtrosApplication().getConfiguration().getInt(ConfKeys.SEARCH_LAST_COUNT, 30);
    while (model.getSize() > maxCount) {
        model.removeElementAt(model.getSize() - 1);
    }

    context.setSearchMatcher(searchMatcher);
    SearchResult searchNext = searchEngine.searchNext(context, nextRowProvider);
    if (searchNext.isFound()) {
        int row = table.convertRowIndexToView(searchNext.getRow());
        Rectangle rect = table.getCellRect(row, 0, true);
        table.scrollRectToVisible(rect);
        table.clearSelection();
        table.setRowSelectionInterval(row, row);
        statusObserver.updateStatus(String.format("Found at row %d", row), StatusObserver.LEVEL_NORMAL);
        if (markFound) {
            lvPanel.getDataTableModel().markRows(markerColors, table.convertRowIndexToModel(row));
        }

        scrollToSearchResult(
                searchMatcher.getFoundTextFragments(
                        lvPanel.getDataTableModel().getLogData(table.convertRowIndexToModel(row))),
                lvPanel.getLogViewPanel().getLogDetailTextArea());
    } else {
        statusObserver.updateStatus(String.format("\"%s\" not found", text), StatusObserver.LEVEL_WARNING);
    }
}

From source file:pl.otros.logview.gui.LogViewPanelWrapper.java

private void addRowScroller() {
    dataTableModel.addTableModelListener(new TableModelListener() {

        @Override//from  w w w .j  av  a2 s . c  o  m
        public void tableChanged(final TableModelEvent e) {
            if (follow.isSelected() && e.getType() == TableModelEvent.INSERT) {
                final Runnable r = new Runnable() {

                    @Override
                    public void run() {
                        try {
                            JTable table = logViewPanel.getTable();
                            int row = table.getRowCount() - 1;
                            if (row > 0) {
                                Rectangle rect = table.getCellRect(row, 0, true);
                                table.scrollRectToVisible(rect);
                                table.clearSelection();
                                table.setRowSelectionInterval(row, row);
                            }
                        } catch (IllegalArgumentException iae) {
                            // ignore..out of bounds
                            iae.printStackTrace();
                        }
                    }
                };
                // Wait for JViewPort size update
                // TODO Find way to invoke this listener after viewport is notified about changes
                Runnable r2 = new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException ignore) {
                        }
                        SwingUtilities.invokeLater(r);
                    }
                };
                new Thread(r2).start();
            }
        }
    });
}