Example usage for javax.swing JTable getSelectedColumn

List of usage examples for javax.swing JTable getSelectedColumn

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Set the tab and return behavior for a table.
 *//*from  w  ww. j av a2  s.  c  o m*/
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: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  w  w .  j ava2s.  c  o  m*/
        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();

}

From source file:org.eclipse.jubula.rc.swing.listener.RecordActions.java

/**
 * select cell/*from  w  w  w  .  ja  va  2 s  .  com*/
 * @param jtbl JTable
 * @param id IComponentIdentifier
 * @param clickcount int
 * @param a Action
 * @param mouseButton the mouse button used
 */
protected void selectTableCell(JTable jtbl, IComponentIdentifier id, int clickcount, Action a,
        int mouseButton) {
    int row = jtbl.getSelectedRow();
    int column = jtbl.getSelectedColumn();
    int count = clickcount;
    if (count < 1) {
        count = 1;
    }
    String clCount = (new Integer(count).toString());
    String rowStr = (new Integer(row + 1)).toString();
    String columnStr = (new Integer(column + 1)).toString();
    List tblValues = new LinkedList();
    tblValues.add(rowStr);
    tblValues.add(MatchUtil.EQUALS);
    tblValues.add(columnStr);
    tblValues.add(MatchUtil.EQUALS);
    tblValues.add(clCount);
    tblValues.add("50"); //$NON-NLS-1$
    tblValues.add("percent"); //$NON-NLS-1$
    tblValues.add("50"); //$NON-NLS-1$
    tblValues.add("percent"); //$NON-NLS-1$
    tblValues.add(Constants.REC_EXT_SELECTION);
    tblValues.add(String.valueOf(mouseButton));

    String logName = createLogicalName(jtbl, id);

    createCAP(a, id, tblValues, logName);
}

From source file:org.isatools.isacreator.gui.formelements.SubForm.java

protected void setupTableTabBehaviour() {
    InputMap im = scrollTable.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 = scrollTable.getActionMap().get(im.get(tab));
    Action newTabAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int rowSel = scrollTable.getSelectedRow();
            int colSel = scrollTable.getSelectedColumn();

            if (rowSel == (scrollTable.getRowCount() - 1)) {
                scrollTable.setRowSelectionInterval(0, 0);

                if ((colSel + 1) == scrollTable.getColumnCount()) {
                    scrollTable.setColumnSelectionInterval(0, 0);
                } else {
                    scrollTable.setColumnSelectionInterval(colSel + 1, colSel + 1);
                }/*from ww  w. jav  a  2s.co m*/
            } else {
                rowSel = rowSel + 1;
                scrollTable.setRowSelectionInterval(rowSel, rowSel);

                if (colSel > -1) {
                    scrollTable.setColumnSelectionInterval(colSel, colSel);
                }
            }

            scrollTable.scrollRectToVisible(scrollTable.getCellRect(rowSel, colSel, true));

            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();
            }
        }
    };
    scrollTable.getActionMap().put(im.get(tab), newTabAction);
}

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

/**
 * Setup the JTable with its desired characteristics
 *//*from  w  w  w .  j a  v  a2s.c  o 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:org.nuclos.client.ui.collect.result.ResultController.java

private ListSelectionListener newListSelectionListener(final JTable tblResult) {
    return new ListSelectionListener() {
        @Override/* w  ww .  jav a  2 s.c  o m*/
        public void valueChanged(ListSelectionEvent ev) {
            try {
                final ListSelectionModel lsm = (ListSelectionModel) ev.getSource();

                final CollectStateModel<?> clctstatemodel = clctctl.getCollectStateModel();
                if (clctstatemodel.getOuterState() == CollectState.OUTERSTATE_RESULT) {
                    final int iResultMode = CollectStateModel.getResultModeFromSelectionModel(lsm);
                    if (iResultMode != clctctl.getCollectStateModel().getResultMode()) {
                        clctctl.setCollectState(CollectState.OUTERSTATE_RESULT, iResultMode);
                    }
                }

                if (!ev.getValueIsAdjusting()) {
                    // Autoscroll selection. It's okay to do that here rather than in the CollectStateListener.
                    if (!lsm.isSelectionEmpty() && tblResult.getAutoscrolls()) {
                        // ensure that the last selected row is visible:
                        final int iRowIndex = lsm.getLeadSelectionIndex();
                        final int iColIndex = tblResult.getSelectedColumn();
                        final Rectangle rectCell = tblResult.getCellRect(iRowIndex,
                                iColIndex != -1 ? iColIndex : 0, true);
                        if (rectCell != null) {
                            tblResult.scrollRectToVisible(rectCell);
                        }
                    }
                }
            } catch (CommonBusinessException ex) {
                Errors.getInstance().showExceptionDialog(clctctl.getTab(), ex);
            }
        } // valueChanged
    };
}