Example usage for javax.swing JTable getCellEditor

List of usage examples for javax.swing JTable getCellEditor

Introduction

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

Prototype

public TableCellEditor getCellEditor() 

Source Link

Document

Returns the active cell editor, which is null if the table is not currently editing.

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);

    // Enable the ability to select a single cell
    table.setColumnSelectionAllowed(true);
    table.setRowSelectionAllowed(true);//from  ww w  .  java  2  s .  c  om

    if (table.getCellEditor() != null) {
        table.getCellEditor().stopCellEditing();
    }
}

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);//from  ww w . j  a  v  a2  s  .  c om

    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.googlecode.vfsjfilechooser2.filepane.VFSFilePane.java

public JPanel createDetailsView() {
    final VFSJFileChooser chooser = getFileChooser();

    JPanel p = new JPanel(new BorderLayout());

    final JTable detailsTable = new JTable(getDetailsTableModel()) {
        // Handle Escape key events here
        @Override//from   www  .j av a  2s. c o  m
        protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
            if ((e.getKeyCode() == KeyEvent.VK_ESCAPE) && (getCellEditor() == null)) {
                // We are not editing, forward to filechooser.
                chooser.dispatchEvent(e);

                return true;
            }

            return super.processKeyBinding(ks, e, condition, pressed);
        }

        @Override
        public void tableChanged(TableModelEvent e) {
            super.tableChanged(e);

            if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                // update header with possibly changed column set
                updateDetailsColumnModel(this);
            }
        }
    };

    //        detailsTable.setRowSorter(getRowSorter());
    detailsTable.setAutoCreateColumnsFromModel(false);
    detailsTable.setComponentOrientation(chooser.getComponentOrientation());
    //detailsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    detailsTable.setShowGrid(false);
    detailsTable.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);

    //        detailsTable.addKeyListener(detailsKeyListener);
    Font font = list.getFont();
    detailsTable.setFont(font);
    detailsTable.setIntercellSpacing(new Dimension(0, 0));

    TableCellRenderer headerRenderer = new AlignableTableHeaderRenderer(
            detailsTable.getTableHeader().getDefaultRenderer());
    detailsTable.getTableHeader().setDefaultRenderer(headerRenderer);

    TableCellRenderer cellRenderer = new DetailsTableCellRenderer(chooser);
    detailsTable.setDefaultRenderer(Object.class, cellRenderer);

    // So that drag can be started on a mouse press
    detailsTable.getColumnModel().getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    detailsTable.addMouseListener(getMouseHandler());
    // No need to addListSelectionListener because selections are forwarded
    // to our JList.

    // 4835633 : tell BasicTableUI that this is a file list
    detailsTable.putClientProperty("Table.isFileList", Boolean.TRUE);

    if (listViewWindowsStyle) {
        detailsTable.addFocusListener(repaintListener);
    }

    JTableHeader header = detailsTable.getTableHeader();
    header.setUpdateTableInRealTime(true);
    header.addMouseListener(detailsTableModel.new ColumnListener());
    header.setReorderingAllowed(true);

    // TAB/SHIFT-TAB should transfer focus and ENTER should select an item.
    // We don't want them to navigate within the table
    ActionMap am = SwingUtilities.getUIActionMap(detailsTable);
    am.remove("selectNextRowCell");
    am.remove("selectPreviousRowCell");
    am.remove("selectNextColumnCell");
    am.remove("selectPreviousColumnCell");
    detailsTable.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
    detailsTable.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);

    JScrollPane scrollpane = new JScrollPane(detailsTable);
    scrollpane.setComponentOrientation(chooser.getComponentOrientation());
    LookAndFeel.installColors(scrollpane.getViewport(), "Table.background", "Table.foreground");

    // Adjust width of first column so the table fills the viewport when
    // first displayed (temporary listener).
    scrollpane.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            JScrollPane sp = (JScrollPane) e.getComponent();
            fixNameColumnWidth(sp.getViewport().getSize().width);
            sp.removeComponentListener(this);
        }
    });

    // 4835633.
    // If the mouse is pressed in the area below the Details view table, the
    // event is not dispatched to the Table MouseListener but to the
    // scrollpane.  Listen for that here so we can clear the selection.
    scrollpane.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            JScrollPane jsp = ((JScrollPane) e.getComponent());
            JTable table = (JTable) jsp.getViewport().getView();

            if (!e.isShiftDown()
                    || (table.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION)) {
                clearSelection();

                TableCellEditor tce = table.getCellEditor();

                if (tce != null) {
                    tce.stopCellEditing();
                }
            }
        }
    });

    detailsTable.setForeground(list.getForeground());
    detailsTable.setBackground(list.getBackground());

    if (listViewBorder != null) {
        scrollpane.setBorder(listViewBorder);
    }

    p.add(scrollpane, BorderLayout.CENTER);

    detailsTableModel.fireTableStructureChanged();

    return p;
}

From source file:fi.hoski.remote.ui.Admin.java

private void editReservations(final EventType eventType) {
    final Event event = chooseEvent(eventType, "CHOOSE");
    if (event != null) {
        final String eventTitle = TextUtil.getText(event.getEventType().name()) + " "
                + event.get(Event.EventDate);
        safeTitle = frame.getTitle();// w w  w  .  j av a  2s  .c  om
        frame.setTitle(eventTitle);
        reservationList = dss.getReservations(event);
        selectedReservations = new ArrayList<Reservation>();
        unSelectedReservations = new ArrayList<Reservation>();
        if (Event.isInspection(eventType)) {
            for (Reservation reservation : reservationList) {
                Boolean inspected = (Boolean) reservation.get(Reservation.INSPECTED);
                if (inspected != null && inspected) {
                    selectedReservations.add(reservation);
                } else {
                    unSelectedReservations.add(reservation);
                }
            }
        } else {
            for (Reservation reservation : reservationList) {
                Long order = (Long) reservation.get(Reservation.ORDER);
                if (order != null && order != 0) {
                    selectedReservations.add(reservation);
                } else {
                    unSelectedReservations.add(reservation);
                }
            }
        }
        DataObjectModel baseModel = Reservation.getModel(eventType);
        DataObjectModel unorderedModel = null;
        DataObjectModel orderedModel = null;
        switch (eventType) {
        case LAUNCH:
        case LIFT:
        case HULL_INSPECTION:
            unorderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
            orderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR);
            break;
        case INSPECTION:
            unorderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR,
                    Reservation.EMAIL, Reservation.MOBILEPHONE, Reservation.DOCK, Reservation.DOCKNUMBER,
                    Reservation.INSPECTION_GASS, Reservation.INSPECTOR);
            orderedModel = baseModel.hide(Reservation.BOAT, Reservation.INSPECTED, Reservation.CREATOR,
                    Reservation.EMAIL, Reservation.MOBILEPHONE, Reservation.DOCK, Reservation.DOCKNUMBER,
                    Reservation.NOTES);
            break;
        }

        final DataObjectListTableModel<Reservation> unorderedTableModel = new DataObjectListTableModel<Reservation>(
                unorderedModel, unSelectedReservations);
        final JTable unorderedtable = new FitTable(unorderedTableModel);
        TableSelectionHandler tsh1 = new TableSelectionHandler(unorderedtable);
        unorderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
        unorderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());

        unorderedtable.addKeyListener(unorderedTableModel.getRemover(dss));
        unorderedtable.setDragEnabled(true);
        unorderedtable.setDropMode(DropMode.INSERT_ROWS);
        TransferHandler unorderedTransferHandler = new DataObjectTransferHandler<Reservation>(
                unorderedTableModel);
        unorderedtable.setTransferHandler(unorderedTransferHandler);

        final DataObjectListTableModel<Reservation> orderedTableModel = new DataObjectListTableModel<Reservation>(
                orderedModel, selectedReservations);
        orderedTableModel.setEditable(Reservation.INSPECTION_CLASS, Reservation.INSPECTION_GASS,
                Reservation.BASICINSPECTION, Reservation.INSPECTOR);
        final JTable orderedtable = new FitTable(orderedTableModel);
        TableSelectionHandler tsh2 = new TableSelectionHandler(orderedtable);
        orderedtable.setDefaultRenderer(String.class, new StringTableCellRenderer());
        orderedtable.setDefaultRenderer(Text.class, new TextTableCellRenderer());

        orderedtable.addKeyListener(orderedTableModel.getRemover(dss));
        orderedtable.setDragEnabled(true);
        orderedtable.setDropMode(DropMode.INSERT_ROWS);
        TransferHandler orderedTransferHandler = new DataObjectTransferHandler<Reservation>(orderedTableModel);
        orderedtable.setTransferHandler(orderedTransferHandler);
        if (Event.isInspection(eventType)) {
            unorderedtable.setAutoCreateRowSorter(true);
            orderedtable.setAutoCreateRowSorter(true);
        }
        leftPane = new JScrollPane();
        leftPane.setViewport(new InfoViewport(TextUtil.getText(eventType.name() + "-leftPane")));
        leftPane.setViewportView(unorderedtable);
        leftPane.setTransferHandler(unorderedTransferHandler);

        rightPane = new JScrollPane();
        rightPane.setViewport(new InfoViewport(TextUtil.getText(eventType.name() + "-rightPane")));
        rightPane.setViewportView(orderedtable);
        rightPane.setTransferHandler(orderedTransferHandler);

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPane, rightPane);
        splitPane.setDividerLocation(0.5);
        menuReservation.setEnabled(false);
        safeContainer = frame.getContentPane();
        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.add(splitPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        contentPane.add(buttonPanel, BorderLayout.SOUTH);

        JButton saveButton = new JButton();
        TextUtil.populate(saveButton, "SAVE");
        saveButton.setEnabled(!Event.isInspection(eventType));
        ActionListener saveAction = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                saveReservations();
            }
        };
        saveButton.addActionListener(saveAction);
        buttonPanel.add(saveButton);

        switch (eventType) {
        case INSPECTION: {
            if (privileged) {
                JButton inspectButton = new JButton();
                TextUtil.populate(inspectButton, "SET INSPECTED");
                ActionListener inspectAction = new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        TableCellEditor cellEditor = orderedtable.getCellEditor();
                        if (cellEditor != null) {
                            cellEditor.stopCellEditing();
                        }
                        try {
                            setAsInspected();
                        } catch (SQLException | ClassNotFoundException ex) {
                            ex.printStackTrace();
                            JOptionPane.showMessageDialog(null, ex.getMessage());
                        }
                    }
                };
                inspectButton.addActionListener(inspectAction);
                buttonPanel.add(inspectButton);
            }

            JButton addBoat = new JButton();
            TextUtil.populate(addBoat, "ADD BOAT");
            ActionListener addBoatAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Reservation reservation = reservate(eventType, event);
                    if (reservation != null) {
                        reservationList.add(reservation);
                        unSelectedReservations.add(reservation);
                        unorderedTableModel.fireTableDataChanged();
                    }
                }
            };
            addBoat.addActionListener(addBoatAction);
            buttonPanel.add(addBoat);

            JButton printTypeButton = new JButton();
            TextUtil.populate(printTypeButton, "PRINT");
            ActionListener printTypeAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printNameBoatTypeOrder(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            printTypeButton.addActionListener(printTypeAction);
            buttonPanel.add(printTypeButton);

            JButton printDockButton = new JButton();
            TextUtil.populate(printDockButton, "PRINT DOCK ORDER");
            ActionListener printDockAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printDockOrder(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            printDockButton.addActionListener(printDockAction);
            buttonPanel.add(printDockButton);

        }
            break;
        case HULL_INSPECTION: {
            JButton print = new JButton();
            TextUtil.populate(print, "PRINT");
            ActionListener printAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printAlphaOrder(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            print.addActionListener(printAction);
            buttonPanel.add(print);

        }
            break;
        case LAUNCH:
        case LIFT: {
            JButton addBoat = new JButton();
            TextUtil.populate(addBoat, "ADD BOAT");
            ActionListener addBoatAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    Reservation reservation = reservate(eventType, event);
                    if (reservation != null) {
                        reservationList.add(reservation);
                        unSelectedReservations.add(reservation);
                        unorderedTableModel.fireTableDataChanged();
                    }
                }
            };
            addBoat.addActionListener(addBoatAction);
            buttonPanel.add(addBoat);

            JButton printBrief = new JButton();
            TextUtil.populate(printBrief, "BRIEF PRINT");
            ActionListener printBriefAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        printOrderBrief(eventTitle);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            printBrief.addActionListener(printBriefAction);
            buttonPanel.add(printBrief);

            JButton print = new JButton();
            TextUtil.populate(print, "PRINT");
            ActionListener printAction = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        if (eventType == EventType.LAUNCH) {
                            printLaunchOrder(eventTitle);
                        } else {
                            printLiftOrder(eventTitle);
                        }
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                    }
                }
            };
            print.addActionListener(printAction);
            buttonPanel.add(print);
        }
            break;
        }

        JButton cancelButton = new JButton();
        TextUtil.populate(cancelButton, "CANCEL");
        ActionListener cancelAction = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                cancel();
            }
        };
        cancelButton.addActionListener(cancelAction);
        buttonPanel.add(cancelButton);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setVisible(true);
        KeyListener keyListener = new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 10) {
                    int selectedRow = unorderedtable.getSelectedRow();
                    if (selectedRow != -1) {
                        RowSorter<? extends TableModel> rowSorter = unorderedtable.getRowSorter();
                        if (rowSorter != null) {
                            selectedRow = rowSorter.convertRowIndexToModel(selectedRow);
                        }
                        Reservation reservation = unorderedTableModel.getObject(selectedRow);
                        orderedTableModel.add(reservation);
                        unorderedTableModel.remove(reservation);
                        e.consume();
                        unorderedtable.changeSelection(selectedRow, 0, false, false);
                    }
                }
            }
        };
        unorderedtable.addKeyListener(keyListener);
        unorderedtable.requestFocusInWindow();
    }
}

From source file:org.apache.cayenne.modeler.util.DbAttributePathComboBoxEditor.java

@Override
protected void enterPressed(JTable table) {
    String dbAttributePath = ((JTextComponent) comboBoxPathChooser.getEditor().getEditorComponent()).getText();
    Object currentNode = getCurrentNode(dbAttributePath);

    String[] pathStrings = dbAttributePath.split(Pattern.quote("."));
    String lastStringInPath = pathStrings[pathStrings.length - 1];
    if (ModelerUtil.getObjectName(currentNode).equals(lastStringInPath) && currentNode instanceof DbAttribute) {
        // in this case choose is made.. we save data

        if (table.getCellEditor() != null) {
            table.getCellEditor().stopCellEditing();
            if (dbAttributePath.equals(savePath)) {
                return;
            }/*www. ja va 2s  . c  om*/
            model.setUpdatedValueAt(dbAttributePath, row, DB_ATTRIBUTE_PATH_COLUMN);
            model.getAttribute(row).getValue().setDbAttributePath(dbAttributePath);
        }
    } else if (ModelerUtil.getObjectName(currentNode).equals(lastStringInPath)
            && currentNode instanceof DbRelationship) {
        // in this case we add dot  to pathString (if it is missing) and show variants for currentNode

        if (dbAttributePath.charAt(dbAttributePath.length() - 1) != '.') {
            dbAttributePath = dbAttributePath + '.';
            previousEmbeddedLevel = StringUtils.countMatches(dbAttributePath, ".");
            ((JTextComponent) (comboBoxPathChooser).getEditor().getEditorComponent()).setText(dbAttributePath);
        }
        List<String> currentNodeChildren = new ArrayList<>();
        currentNodeChildren.addAll(getChildren(getCurrentNode(dbAttributePath), dbAttributePath));
        comboBoxPathChooser.setModel(new DefaultComboBoxModel(currentNodeChildren.toArray()));
        comboBoxPathChooser.setSelectedItem(dbAttributePath);
        comboBoxPathChooser.showPopup();
        comboBoxPathChooser.setPopupVisible(true);
    }
}

From source file:org.isatools.isacreator.api.utils.SpreadsheetUtils.java

public static void stopCellEditingInTable(JTable table) {
    if (table.getEditingColumn() != -1) {
        // the ontology cell editor is a JFrame, so closing it is useless since it will close when it loses focus anyway.
        if (!(table.getCellEditor() instanceof OntologyCellEditor)) {
            table.getCellEditor(table.getEditingRow(), table.getEditingColumn()).stopCellEditing();
        }/*from   w  w  w  .  j av a  2  s. c om*/
    }
}

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
 *//*from   w  w w  .j  a  v  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);
            }
        }
    });
}

From source file:org.pentaho.ui.xul.swing.tags.SwingTree.java

private TableCellEditor getCellEditor(final SwingTreeCol col) {
    return new DefaultCellEditor(new JComboBox()) {

        JComponent control;/*from   www  .  j a  va2 s .c om*/

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
                final int row, final int column) {
            Component comp;
            ColumnType colType = col.getColumnType();
            if (colType == ColumnType.DYNAMIC) {
                colType = ColumnType.valueOf(extractDynamicColType(elements.toArray()[row], column));
            }

            final XulTreeCell cell = getRootChildren().getItem(row).getRow().getCell(column);
            switch (colType) {
            case CHECKBOX:
                final JCheckBox checkbox = new JCheckBox();
                final JTable tbl = table;
                checkbox.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        SwingTree.this.table.setValueAt(checkbox.isSelected(), row, column);
                        tbl.getCellEditor().stopCellEditing();
                    }
                });

                control = checkbox;
                if (value instanceof String) {
                    checkbox.setSelected(((String) value).equalsIgnoreCase("true")); //$NON-NLS-1$
                } else if (value instanceof Boolean) {
                    checkbox.setSelected((Boolean) value);
                } else if (value == null) {
                    checkbox.setSelected(false);
                }
                if (isSelected) {
                    checkbox.setBackground(Color.LIGHT_GRAY);
                }
                comp = checkbox;
                checkbox.setEnabled(!cell.isDisabled());
                break;
            case EDITABLECOMBOBOX:
            case COMBOBOX:
                Vector val = (value != null && value instanceof Vector) ? (Vector) value : new Vector();
                final JComboBox comboBox = new JComboBox(val);

                if (isSelected) {
                    comboBox.setBackground(Color.LIGHT_GRAY);
                }

                if (colType == ColumnType.EDITABLECOMBOBOX) {

                    comboBox.setEditable(true);
                    final JTextComponent textComp = (JTextComponent) comboBox.getEditor().getEditorComponent();

                    textComp.addKeyListener(new KeyListener() {
                        private String oldValue = ""; //$NON-NLS-1$

                        public void keyPressed(KeyEvent e) {
                            oldValue = textComp.getText();
                        }

                        public void keyReleased(KeyEvent e) {
                            if (oldValue != null && !oldValue.equals(textComp.getText())) {
                                SwingTree.this.table.setValueAt(textComp.getText(), row, column);

                                oldValue = textComp.getText();
                            } else if (oldValue == null) {
                                // AWT error where sometimes the keyReleased is fired before keyPressed.
                                oldValue = textComp.getText();
                            } else {
                                logger.debug("Special key pressed, ignoring"); //$NON-NLS-1$
                            }
                        }

                        public void keyTyped(KeyEvent e) {
                        }
                    });

                    comboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                            // if(textComp.hasFocus() == false && comboBox.hasFocus()){
                            SwingTree.logger.debug("Setting ComboBox value from editor: " //$NON-NLS-1$
                                    + comboBox.getSelectedItem() + ", " + row + ", " + column); //$NON-NLS-1$ //$NON-NLS-2$

                            SwingTree.this.table.setValueAt(comboBox.getSelectedIndex(), row, column);
                            // }
                        }
                    });
                } else {
                    comboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {

                            SwingTree.logger.debug("Setting ComboBox value from editor: " //$NON-NLS-1$
                                    + comboBox.getSelectedItem() + ", " + row + ", " + column); //$NON-NLS-1$ //$NON-NLS-2$

                            SwingTree.this.table.setValueAt(comboBox.getSelectedIndex(), row, column);
                        }
                    });
                }

                control = comboBox;
                comboBox.setEnabled(!cell.isDisabled());
                comp = comboBox;
                break;
            case LABEL:
                JLabel lbl = new JLabel(cell.getLabel());
                comp = lbl;
                control = lbl;
                break;
            case CUSTOM:
                return new CustomCellEditorWrapper(cell, customEditors.get(col.getType()));
            default:
                final JTextField label = new JTextField((String) value);

                label.getDocument().addDocumentListener(new DocumentListener() {

                    public void changedUpdate(DocumentEvent arg0) {
                        SwingTree.this.table.setValueAt(label.getText(), row, column);
                    }

                    public void insertUpdate(DocumentEvent arg0) {
                        SwingTree.this.table.setValueAt(label.getText(), row, column);
                    }

                    public void removeUpdate(DocumentEvent arg0) {
                        SwingTree.this.table.setValueAt(label.getText(), row, column);
                    }

                });
                if (isSelected) {
                    label.setOpaque(true);
                    // label.setBackground(Color.LIGHT_GRAY);
                }

                control = label;
                comp = label;
                label.setEnabled(!cell.isDisabled());
                label.setDisabledTextColor(Color.DARK_GRAY);
                break;
            }

            return comp;
        }

        @Override
        public Object getCellEditorValue() {
            if (control instanceof JCheckBox) {
                return ((JCheckBox) control).isSelected();
            } else if (control instanceof JComboBox) {
                JComboBox box = (JComboBox) control;
                if (box.isEditable()) {
                    return ((JTextComponent) box.getEditor().getEditorComponent()).getText();
                } else {
                    return box.getSelectedIndex();
                }
            } else if (control instanceof JTextField) {
                return ((JTextField) control).getText();
            } else {
                return ((JLabel) control).getText();
            }
        }

    };

}