Example usage for javax.swing JTable editCellAt

List of usage examples for javax.swing JTable editCellAt

Introduction

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

Prototype

public boolean editCellAt(int row, int column) 

Source Link

Document

Programmatically starts editing the cell at row and column, if those indices are in the valid range, and the cell at those indices is editable.

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.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);/* w w w. ja  v  a  2s  . c  o  m*/

    int row = 1;
    int col = 3;
    boolean success = table.editCellAt(row, col);
    if (success) {
        boolean toggle = false;
        boolean extend = false;
        table.changeSelection(row, col, toggle, extend);
    }
}

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.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);/* w ww.j  a  va2  s .  co  m*/

    int row = 1;
    int col = 3;
    boolean success = table.editCellAt(row, col);
    if (success) {
        boolean toggle = false;
        boolean extend = false;
        table.changeSelection(row, col, toggle, extend);
    }
    if (table.getCellEditor() != null) {
        table.getCellEditor().cancelCellEditing();
    }
}

From source file:com.aw.swing.mvp.ui.painter.PainterMessages.java

public static void paintException(Throwable exception, boolean showError) {

    //        cleanException();

    ExceptionPainter exceptionPainter = getExceptionPainter(exception);

    JComponent jComponentWithFocus = null;
    if (exception instanceof AWGridValidationException) {
        jComponentWithFocus = ((AWGridValidationException) exception).getJComponent();
    } else if (exception instanceof AWBusinessException) {
        AWBusinessException bExc = (AWBusinessException) exception;
        String visualCmpName = bExc.getVisualCmpName();
        if (StringUtils.hasText(visualCmpName)) {
            jComponentWithFocus = getComponentBasedOn(visualCmpName);
        }/*  w  w  w  . j  a  v  a2s.  co  m*/
    } else {
        oldComponents = exceptionPainter.getBindingComponents(exception);
        logger.debug("Component with validation fail <" + oldComponents.size() + "> ");
        boolean requestFocus = true;
        if (exception instanceof AWSwingException) {
            requestFocus = ((AWSwingException) exception).isRequestFocus();
        }
        if (requestFocus) {
            jComponentWithFocus = getComponentThatRecivedFocus(exception);
        }
        ErrorPainter errorPainter = SwingContext.getErrorPainter();
        errorPainter.paintError(oldComponents);
    }
    /**
     * Showing the component before showing the message
     */
    if (jComponentWithFocus != null) {
        new UIComponentManager().requestFocus(jComponentWithFocus);
    }

    if (showError) {
        List messagesError = exceptionPainter.getMessagesError(exception);
        String message = buildCustomMessage(messagesError);
        // todo verificar si funcions
        //            if (messagesError.size() >= maxMessagesInPanel || message.length()>100) {
        MsgDisplayer.showErrorMessage(message);
        //            } else {
        //                SwingContext.getCurrentPst().getViewMgr().getLayout().showErrorMessage(message);
        //            }
    }

    if (jComponentWithFocus != null) {
        new UIComponentManager().requestFocus(jComponentWithFocus);
        if (exception instanceof AWGridValidationException) {
            AWGridValidationException gridValidationException = (AWGridValidationException) exception;
            JTable jTable = (JTable) gridValidationException.getJComponent();
            Cell cell = gridValidationException.getCell();
            if (cell != null) {
                new UIComponentManager().setSelectedRow(jTable, cell.getRow());
                jTable.editCellAt(cell.getRow(), cell.getCol());
            }

        }
    }

}

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);
                }/*w w w.  j ava 2  s. c  o  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 av  a 2s.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.common.Utils.java

/**
 * sets the input focus to a certain collectable component in a LayoutML mask.
 * @param eafnInitialFocus entity name and field name of the component that is to receive to focus. The entity name is
 * null, if the component is not in a subform.
 * @param clctcompprovider map of all collectable components in the layout
 * @param mpsubformctl map of all subformcontrollers
 * @param frame frame of the layout (for possible warning dialogs only)
 * @param bShowWarnings displays warnings for components not found for focussing
 * @precondition eafnInitialFocus != null
 *//* w  ww  . j av a  2  s .  c o m*/
public static void setInitialComponentFocus(EntityAndFieldName eafnInitialFocus,
        final CollectableComponentsProvider clctcompprovider,
        final Map<String, ? extends SubFormController> mpsubformctl, final MainFrameTab frame,
        final boolean bShowWarnings) {

    final String sInitialFocusEntityName = eafnInitialFocus.getEntityName();
    final String sInitialFocusFieldName = eafnInitialFocus.getFieldName();

    // Must be invoked later, else focus is not set with compound components like LOVs
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                if (sInitialFocusEntityName == null) {
                    if (sInitialFocusFieldName != null) {
                        final Collection<CollectableComponent> collclctcomp = clctcompprovider
                                .getCollectableComponentsFor(sInitialFocusFieldName);
                        if (collclctcomp.isEmpty()) {
                            if (bShowWarnings) {
                                final String sMessage = SpringLocaleDelegate.getInstance().getMessage(
                                        "ClientUtils.1",
                                        "Das angegebene Feld f\u00fcr den initialen Fokus existiert nicht.");
                                JOptionPane
                                        .showMessageDialog(
                                                frame, sMessage, SpringLocaleDelegate.getInstance()
                                                        .getMessage("ClientUtils.2", "Hinweis"),
                                                JOptionPane.WARNING_MESSAGE);
                            }
                        } else {
                            final CollectableComponent clctcomp = collclctcomp.iterator().next();
                            final JComponent compFocus = clctcomp.getFocusableComponent();
                            compFocus.requestFocusInWindow();
                        }
                    }
                } else {
                    final SubFormController subformctl = mpsubformctl.get(sInitialFocusEntityName);
                    if (subformctl != null) {
                        final SubForm.SubFormTableModel subformtblmdl = (SubForm.SubFormTableModel) subformctl
                                .getSubForm().getJTable().getModel();

                        final JTable tbl = subformctl.getSubForm().getJTable();
                        final int iColumn = tbl.convertColumnIndexToView(
                                subformtblmdl.findColumnByFieldName(sInitialFocusFieldName));
                        if (iColumn != -1) {
                            if (subformtblmdl.getRowCount() > 0) {
                                tbl.editCellAt(0, iColumn);

                                Component comp = tbl.getCellEditor().getTableCellEditorComponent(tbl,
                                        tbl.getValueAt(0, iColumn), true, 0, iColumn);

                                // Special case for multiline text editor components
                                if (comp instanceof JScrollPane) {
                                    comp = ((JScrollPane) comp).getViewport().getView();
                                }
                                comp.requestFocusInWindow();
                            }
                        } else {
                            if (bShowWarnings) {
                                final String sMessage = SpringLocaleDelegate.getInstance().getMessage(
                                        "ClientUtils.3",
                                        "Das angegebene Feld in der Entit\u00e4t f\u00fcr den initialen Fokus existiert nicht.");
                                JOptionPane
                                        .showMessageDialog(
                                                frame, sMessage, SpringLocaleDelegate.getInstance()
                                                        .getMessage("ClientUtils.2", "Hinweis"),
                                                JOptionPane.WARNING_MESSAGE);
                            }
                        }
                    } else {
                        if (bShowWarnings) {
                            final String sMessage = SpringLocaleDelegate.getInstance().getMessage(
                                    "ClientUtils.4",
                                    "Die angegebene Entit\u00e4t f\u00fcr den initialen Fokus existiert nicht.");
                            JOptionPane.showMessageDialog(frame, sMessage,
                                    SpringLocaleDelegate.getInstance().getMessage("ClientUtils.2", "Hinweis"),
                                    JOptionPane.WARNING_MESSAGE);
                        }
                    }
                }
            } catch (Exception e) {
                LOG.error("setInitialComponentFocus failed: " + e, e);
            }
        }
    });
}