Example usage for javax.swing JTable isCellEditable

List of usage examples for javax.swing JTable isCellEditable

Introduction

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

Prototype

public boolean isCellEditable(int row, int column) 

Source Link

Document

Returns true if the cell at row and column is editable.

Usage

From source file:Main.java

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    if (isSelected) {
        setBackground(UIManager.getColor("Table.selectionBackground"));
    }/* w  w w .j  a v a  2  s  .  c om*/

    if (hasFocus) {
        setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));

        if (table.isCellEditable(row, column)) {
            super.setForeground(UIManager.getColor("Table.focusCellForeground"));
            super.setBackground(UIManager.getColor("Table.focusCellBackground"));
        }
    } else {
        setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
    }
    setText((String) (value));
    table.setRowHeight(row, getPreferredSize().height + row * 10);
    return this;
}

From source file:ExtendedTableCellRenderer.java

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    if (isSelected) {
        super.setForeground(table.getSelectionForeground());
        super.setBackground(table.getSelectionBackground());

    } else {/*ww w . j  av a 2 s .c o m*/
        super.setForeground((unselectedForeground != null) ? unselectedForeground : table.getForeground());
        super.setBackground((unselectedBackground != null) ? unselectedBackground : table.getBackground());
    }

    setFont(table.getFont());

    if (hasFocus) {
        setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
        if (table.isCellEditable(row, column)) {
            super.setForeground(UIManager.getColor("Table.focusCellForeground"));
            super.setBackground(UIManager.getColor("Table.focusCellBackground"));
        }
    } else {
        setBorder(NO_FOCUS_BORDER);
    }

    setValue(value);

    Color background = getBackground();
    boolean colorMatch = (background != null) && (background.equals(table.getBackground())) && table.isOpaque();
    setOpaque(!colorMatch);

    return this;
}

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Set the tab and return behavior for a table.
 *///from w  w  w.j  a  va 2  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:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultPropView.java

private JTable createTable(final ViewState state) {
    JTable table;
    final ModelGraph selected = state.getSelected();
    if (selected != null) {
        final Vector<Vector<String>> rows = new Vector<Vector<String>>();
        ConcurrentHashMap<String, String> keyToGroupMap = new ConcurrentHashMap<String, String>();
        Metadata staticMet = selected.getModel().getStaticMetadata();
        Metadata inheritedMet = selected.getInheritedStaticMetadata(state);
        Metadata completeMet = new Metadata();
        if (staticMet != null) {
            completeMet.replaceMetadata(staticMet.getSubMetadata(state.getCurrentMetGroup()));
        }/*w  w  w.  jav a2  s  .c  o m*/
        if (selected.getModel().getExtendsConfig() != null) {
            for (String configGroup : selected.getModel().getExtendsConfig()) {
                Metadata extendsMetadata = state.getGlobalConfigGroups().get(configGroup).getMetadata()
                        .getSubMetadata(state.getCurrentMetGroup());
                for (String key : extendsMetadata.getAllKeys()) {
                    if (!completeMet.containsKey(key)) {
                        keyToGroupMap.put(key, configGroup);
                        completeMet.replaceMetadata(key, extendsMetadata.getAllMetadata(key));
                    }
                }
            }
        }
        if (inheritedMet != null) {
            Metadata inheritedMetadata = inheritedMet.getSubMetadata(state.getCurrentMetGroup());
            for (String key : inheritedMetadata.getAllKeys()) {
                if (!completeMet.containsKey(key)) {
                    keyToGroupMap.put(key, "__inherited__");
                    completeMet.replaceMetadata(key, inheritedMetadata.getAllMetadata(key));
                }
            }
        }
        List<String> keys = completeMet.getAllKeys();
        Collections.sort(keys);
        for (String key : keys) {
            if (key.endsWith("/envReplace")) {
                continue;
            }
            String values = StringUtils.join(completeMet.getAllMetadata(key), ",");
            Vector<String> row = new Vector<String>();
            row.add(keyToGroupMap.get(key));
            row.add(key);
            row.add(values);
            row.add(Boolean.toString(Boolean.parseBoolean(completeMet.getMetadata(key + "/envReplace"))));
            rows.add(row);
        }
        table = new JTable();// rows, new Vector<String>(Arrays.asList(new
                             // String[] { "key", "values", "envReplace" })));
        table.setModel(new AbstractTableModel() {
            public String getColumnName(int col) {
                switch (col) {
                case 0:
                    return "group";
                case 1:
                    return "key";
                case 2:
                    return "values";
                case 3:
                    return "envReplace";
                default:
                    return null;
                }
            }

            public int getRowCount() {
                return rows.size() + 1;
            }

            public int getColumnCount() {
                return 4;
            }

            public Object getValueAt(int row, int col) {
                if (row >= rows.size()) {
                    return null;
                }
                String value = rows.get(row).get(col);
                if (value == null && col == 3) {
                    return "false";
                }
                if (value == null && col == 0) {
                    return "__local__";
                }
                return value;
            }

            public boolean isCellEditable(int row, int col) {
                if (row >= rows.size()) {
                    return selected.getModel().getStaticMetadata().containsGroup(state.getCurrentMetGroup());
                }
                if (col == 0) {
                    return false;
                }
                String key = rows.get(row).get(1);
                return key == null || (selected.getModel().getStaticMetadata() != null
                        && selected.getModel().getStaticMetadata().containsKey(getKey(key, state)));
            }

            public void setValueAt(Object value, int row, int col) {
                if (row >= rows.size()) {
                    Vector<String> newRow = new Vector<String>(
                            Arrays.asList(new String[] { null, null, null, null }));
                    newRow.add(col, (String) value);
                    rows.add(newRow);
                } else {
                    Vector<String> rowValues = rows.get(row);
                    rowValues.add(col, (String) value);
                    rowValues.remove(col + 1);
                }
                this.fireTableCellUpdated(row, col);
            }

        });
        MyTableListener tableListener = new MyTableListener(state);
        table.getModel().addTableModelListener(tableListener);
        table.getSelectionModel().addListSelectionListener(tableListener);
    } else {
        table = new JTable(new Vector<Vector<String>>(),
                new Vector<String>(Arrays.asList(new String[] { "key", "values", "envReplace" })));
    }

    // table.setFillsViewportHeight(true);
    table.setSelectionBackground(Color.cyan);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    TableCellRenderer cellRenderer = new TableCellRenderer() {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel field = new JLabel((String) value);
            if (column == 0) {
                field.setForeground(Color.gray);
            } else {
                if (isSelected) {
                    field.setBorder(new EtchedBorder(1));
                }
                if (table.isCellEditable(row, 1)) {
                    field.setForeground(Color.black);
                } else {
                    field.setForeground(Color.gray);
                }
            }
            return field;
        }

    };
    TableColumn groupCol = table.getColumnModel().getColumn(0);
    groupCol.setPreferredWidth(75);
    groupCol.setCellRenderer(cellRenderer);
    TableColumn keyCol = table.getColumnModel().getColumn(1);
    keyCol.setPreferredWidth(200);
    keyCol.setCellRenderer(cellRenderer);
    TableColumn valuesCol = table.getColumnModel().getColumn(2);
    valuesCol.setPreferredWidth(300);
    valuesCol.setCellRenderer(cellRenderer);
    TableColumn envReplaceCol = table.getColumnModel().getColumn(3);
    envReplaceCol.setPreferredWidth(75);
    envReplaceCol.setCellRenderer(cellRenderer);

    table.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3 && DefaultPropView.this.table.getSelectedRow() != -1) {
                int row = DefaultPropView.this.table.getSelectedRow();// rowAtPoint(DefaultPropView.this.table.getMousePosition());
                String key = getKey((String) DefaultPropView.this.table.getValueAt(row, 1), state);
                Metadata staticMet = state.getSelected().getModel().getStaticMetadata();
                override.setVisible(staticMet == null || !staticMet.containsKey(key));
                delete.setVisible(staticMet != null && staticMet.containsKey(key));
                tableMenu.show(DefaultPropView.this.table, e.getX(), e.getY());
            }
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    });

    return table;
}

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);
                }/*ww w .  j  a  v  a 2s . c  om*/
            } 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
 *//*ww  w  .  ja  va  2 s . c  om*/
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();
}