JTable with more cell editors??

Hi,
I have a JTbale in which I have two special columns- one with buttons and the other similar to the the color changer from the swing tutorial.
My question is should I have now two renders and two editors in this situation?
Tnax

should I have now two renders and two editors in this situation?You should!
;o)
V.V.

Similar Messages

  • Problem sorting JTable with custom cell editor

    Greetings,
    I have created a JTable with a JComboBox as the cell editor for the first column. However, I couldn't simply set the default cell editor for the column to be a JComboBox, since the values within the list were different for each row. So instead, I implemented a custom cell editor that is basically just a hashtable of cell editors that allows you to have a different editor for each row in the table (based on the ideas in the EachRowEditor I've seen in some FAQs - see the code below). I also used a custom table model that is essentially like the JDBCAdapter in the Java examples that populates the table with a query to a database.
    The problem comes when I try to sort the table using the TableSorter and TableMap classes recommended in the Java Tutorials on JTables. All of the static (uneditable) columns in the JTable sort fine, but the custom cell editor column doesn't sort at all. I think that the problem is that the hashtable storing the cell editors never gets re-ordered, but I can't see a simple way to do that (how to know the old row index verses the new row index after a sort). I think that I could implement this manually, if I knew the old/new indexes...
    Here's the code I use to create the JTable:
    // Create the Table Model
    modelCRM = new ContactTableModel();
    // Create the Table Sorter
    sorterCRM = new TableSorter(modelCRM);
    // Create the table
    tblCRM = new JTable(sorterCRM);
    // Add the event listener for the sorter
    sorterCRM.addMouseListenerToHeaderInTable(tblCRM);
    Then, I populate the column for the custom cell editor like this:
    // Add the combo box for editing company
    TableColumn matchColumn = getTable().getColumn("Match");
    RowCellEditor rowEditor = new RowCellEditor();
    // loop through and build the combobox for each row
    for (int i = 0; i < getTable().getRowCount(); i++) {
    JComboBox cb = new JComboBox();
    cb.addItem("New");
    //... code to populate the combo box (removed for clarity)
    rowEditor.add(i,new DefaultCellEditor(cb, i))); //TF
    } // end for
    matchColumn.setCellEditor(rowEditor);
    Any ideas how to do this, or is there a better way to either sort the JTable or use a combobox with different values for each row? Please let me know if more code would help make this clearer...
    Thanks,
    Ted
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class RowCellEditor implements TableCellEditor
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    public RowCellEditor()
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void add(int row, TableCellEditor editor)
    editors.put(new Integer(row), editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    editor = (TableCellEditor) editors.get(new Integer(row));
    if (editor == null)
    editor = defaultEditor;
    return editor.getTableCellEditorComponent(table,
    value,
    isSelected,
    row,
    column);
    public Object getCellEditorValue() {
    return editor.getCellEditorValue();
    public boolean stopCellEditing() {
    return editor.stopCellEditing();
    public void cancelCellEditing() {
    editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent) {
    return true; //TF
    //return editor.isCellEditable(anEvent);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    return editor.shouldSelectCell(anEvent);
    -------------------

    Well, I found a solution in another post
    (see http://forum.java.sun.com/thread.jsp?forum=57&thread=175984&message=953833#955064 for more details).
    Basically, I use the table sorter to translate the row index for the hashtable of my custom cell editors. I did this by adding this method to the sorter:
    // This method is used to get the correct row for the custom cell
    // editor (after the table has been sorted)
    public int translateRow(int sortedRowIndex)
    checkModel();
    return indexes[sortedRowIndex];
    } // end translateRow()
    Then, when I create the custom cell editor, I pass in a reference to the sorter so that when the getTableCellEditorComponent() method is called I can translate the row to the newly sorted row before returning the editor from the hashtable.

  • Size of combobox in JTable with custom cell editor

    Hi All -
    I have a JTable that displays a combobox in certain cells. I have a custom table model, renderer, and editor. All of that works fine. I render the combobox with the renderer, and then return the combobox as an editor in the editor so that it can drop down and actually be of use. My problem is - I set the size of the combobox with a setBounds call in the renderer, I add it to a panel, and return the panel - because I dont want the combobox to take up the entire space of the cell. This approach fails in the editor. The setBounds and setSize calls have no effect. As soon as you click the combobox, the editor takes over and all of a sudden the combobox resizes to the entire area of the cell. I assume this is because in the editor you arent actually placing anything - your simply returning the "editing form" of the component.
    So - anybody know of a way to work around this? Worst case, I could just allow the combobox to use the entire area of the cell - but it makes it uglier so I figured I would run it by the forums.
    Eric

    Rather than just redirect you to my previous answer from ages ago, I'll just give it again. :-)
    You can actually do this, but you have to get tricky. By default, the dropdown's width will be the same width as the cell... but it doesn't have to be that way. Essentially what you have to do is override the UI (MetalComboBoxUI) for the combo component. In your new customized UI component subclass (that you set the combo to use), modify the the createPopup() method of this UI class, and add your own logic to set the size of the popup before you return it.
    Ideally the size would be based on the computed max width of a rendered item shown in the combo, but really you could set it to whatever just to see how it works.

  • JTable tab key navigation with JComboBox Cell Editors in Java 1.3 & 1.4

    Hello - this is one for the experts!
    I have a JTable which has an editable JComboBox as one of the cell editors for a particular column. Users must be able to navigate through the table using the tab key. After editing a cell a single tab should advance the cell selection to the next column and then the user should just be able to start typing to populate the cell.
    However, i've come across some really frustrating differences between the Swing implementation of JDK1.3.1_09 and JDK 1.4.2_04 which means this behaviour is very different between versions!....
    1. Editing Cells and then advancing to the next column using tab.
    Using standard cell editors (based around JTextFields) in 1.3.1 the user has to press tab twice to traverse to the next column after editing. However, in 1.4.2 a single tab key is enough to move to the next column after editing.
    2. Editable JComboBox editors and and advancing to the next column using tab.
    Using JDK 1.3.1, having entered some text in the editable combo it takes 2 tabs to transfer the selected cell to the next column. With 1.4.2 a single tab while editing the editable combo ends editing and transfers the selection out of the table completely?!?
    With these 2 issues I don't know how to make a single tab key reliably transfer to the next cell, between java versions. Can anyone please help me?!??!
    (i've attached test code below which can be run in both 1.3 and 1.4 and demonstrates the above behaviour.)
    package com.test;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TableTest4 extends JFrame {
         private JTable table;
         private DefaultTableModel tableModel;
         public TableTest4() {
              initFrame();
          * Initialises the test frame.
         public void initFrame() {
              // initialise table
              table = new JTable(10, 5);
              tableModel = (DefaultTableModel) table.getModel();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.setRowHeight(22);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
              JButton dummyBtn1 = new JButton("Dummy Button 1");
              JButton dummyBtn2 = new JButton("Dummy Button 2");
              // initialise frame
              JPanel btnPanel = new JPanel(new GridLayout(2, 1));
              btnPanel.add(dummyBtn1);
              btnPanel.add(dummyBtn2);
              getContentPane().add(btnPanel, BorderLayout.SOUTH);
              // set renderer of first table column to be an editable combobox
              JComboBox editableCombo = new JComboBox();
              editableCombo.setEditable(true);
              TableColumn firstColumn = table.getColumnModel().getColumn(0);
              firstColumn.setCellEditor(new DefaultCellEditor(editableCombo));
         public static void main(String[] args) {
              TableTest4 frame = new TableTest4();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);

    Run the above code in 1.3 and 1.4 and you can see that after editing a cell, the tab key behaviour works differently between versions.
    I don't believe by adding a key listener to the cell editors will have the desired effect.
    I've read other posts and from what i've read it looks like the processKeyBinding method of the JTable can be overridden to manually handle key events.
    Has anyone done this to handle tab key presses so that the same java app running under 1.3 and 1.4 works in the same way ??? I would really appreciate some advice on this as its very frustrating !

  • How can we have a JTable with rounded cells

    I want to create a JTable with circular or oval shaped Cells, can anybody please help me as to how to go about it?
    Thanks in advance

    If you share an Apple ID for purchases then you share all purchases.
    You can hide purchases that are not synced locally (with the cloud icon next to them) to the device here:
    Settings > Music > tuen Show All Music off
    I suggest you create a playlist for each person in iTunes on your computer with only their music on it. Then sync just that playlist to each persons device.

  • Adding rows to Jtable with spanded cells

    I have a jtable with multiple spanded cells. I am using a custom jtable(the code is in http://www2.gol.com/users/tame/swing/examples/JTableExamples4.html) but i need insert a new row when you click on a button.
    I doing this:
    jtable.getModel().addRow(vector);
    but it throws an exception:
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 11 >= 11
    at java.util.Vector.elementAt(Unknown Source)
    at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source)
    at javax.swing.JTable.getValueAt(Unknown Source)
    at javax.swing.JTable.prepareRenderer(Unknown Source)
    at jp.gr.java_conf.tame.swing.table.MultiSpanCellTableUI.paintCell(MultiSpanCellTableUI.java:96)
    at jp.gr.java_conf.tame.swing.table.MultiSpanCellTableUI.paintRow(MultiSpanCellTableUI.java:68)
    at jp.gr.java_conf.tame.swing.table.MultiSpanCellTableUI.paint(MultiSpanCellTableUI.java:39)
    at javax.swing.plaf.ComponentUI.update(Unknown Source)
    at javax.swing.JComponent.paintComponent(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JViewport.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintWithBuffer(Unknown Source)
    at javax.swing.JComponent._paintImmediately(Unknown Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Can anybody help me

    I am using the same code in http://www.codeguru.com/java/articles/139.shtml but it thorws the same exception.
    I need a solution it is urgent

  • Problem with table cell editors - Dropdown by Index, getting lead selection

    Hi experts,
    I have a table editor with 5 columns
    1st column is a Drop Down byIndex.
    My contex looks like this
    AS_DATA(Parent Node cardinality 1.1, selection 0-1)
          HEADER (NODE)
          DETAILS(NODE cardinality 0..n, selection 0-1)
             ACTIVITY_TYPES (NODE cardinality 0..n selection 0-1 ) "node for drop down
             description - attribute
             unit
             quantity
    i have bound details node to table data source.
    i have a tool bar button 'Add Line item' which will add a new line item to the table.
    (i am adding a blank line to the table that is bound to table )
    Its working fine. but when ever i add more than one row, the selection made in the previous rows drop down is lost.
    its initializing. where could be the problem.
    My code
    data LO_ND_INV_TYPE type ref to IF_WD_CONTEXT_NODE.
      data LO_EL_INV_TYPE type ref to IF_WD_CONTEXT_ELEMENT.
      data LS_INV_TYPE type WD_THIS->ELEMENT_INV_TYPE.
      data LV_INV_TYPE type WD_THIS->ELEMENT_INV_TYPE-INV_TYPE.
      data LO_ND_DETAILS type ref to IF_WD_CONTEXT_NODE.
      data LT_DETAILS type WD_THIS->ELEMENTS_DETAILS.
      data LS_DETAILS like line of LT_DETAILS.
      data:  WD_NODE type ref to IF_WD_CONTEXT_NODE,
            LR_ELEMENT type ref to IF_WD_CONTEXT_ELEMENT.
      data LO_ND_INV_PATTERN type ref to IF_WD_CONTEXT_NODE.
      data LO_EL_INV_PATTERN type ref to IF_WD_CONTEXT_ELEMENT.
      data LS_INV_PATTERN type WD_THIS->ELEMENT_INV_PATTERN.
      data LV_INV_PAT type WD_THIS->ELEMENT_INV_PATTERN-INV_TYPE.
      data LO_ND_ACTIVITY_TYPES type ref to IF_WD_CONTEXT_NODE.
      data LT_ACTIVITY_TYPES type WD_THIS->ELEMENTS_ACTIVITY_TYPES.
      data LW_ACTIVITY_TYPES type WD_THIS->ELEMENT_ACTIVITY_TYPES.
        data LO_EL_ACTIVITY_TYPES type ref to IF_WD_CONTEXT_ELEMENT.
    *     navigate from <CONTEXT> to <DETAILS> via lead selection
        LO_ND_DETAILS = WD_CONTEXT->PATH_GET_NODE( PATH = `AS_DATA.DETAILS` ).
        LO_ND_DETAILS->GET_STATIC_ATTRIBUTES_TABLE(
          importing TABLE = LT_DETAILS ).
    * Append an empty row to lt_details
        append LS_DETAILS to LT_DETAILS.
        LO_ND_DETAILS->BIND_TABLE(
        NEW_ITEMS = LT_DETAILS ).
    * Get values for dropdown
    call method WD_ASSIST->GET_ACTIVITY_TYPE
          exporting
            I_INV_CAT_ID     = LV_INV_PAT
          importing
            ET_ACTIVITY_TYPE = LT_ACTIVITY_TYPES.
        LW_ACTIVITY_TYPES-ID = 'Select a Activity type'.
        LW_ACTIVITY_TYPES-TEXT = 'Select a Activity type'.
        insert LW_ACTIVITY_TYPES into LT_ACTIVITY_TYPES index 1.
        loop at LT_DETAILS into LS_DETAILS.
          LV_TABIX = SY-TABIX.
          LR_ELEMENT = LO_ND_DETAILS->GET_ELEMENT( LV_TABIX ).
          WD_NODE = LR_ELEMENT->GET_CHILD_NODE( 'ACTIVITY_TYPES' ).
    *lv_index = wd_node->get_lead_selection_index( ). " it is dumping at this statement when i try to get lead selection
          WD_NODE->BIND_TABLE( NEW_ITEMS =  LT_ACTIVITY_TYPES ). " data for dropdown
        endloop.
    any clue on what am i missing will be appreciated.
    I am getting dump when i try to get the lead selection
    Ajay

    You only have only one option in the DDI to display in the example. when you have multiple values
    i assume that by adding an empty row like this will lose the SELECTION MADE in DDI. (Correct me If i am wrong)
    somehow i believe that we need to bind the DD values using  SET LEAD SELECTION INDEX METHOD FOR THE DDI when they are already selected and trying to BIND.
    *LO_ND_DETAILS->GET_STATIC_ATTRIBUTES_TABLE(*
          *importing TABLE = LT_DETAILS ).*
    ** Append an empty row to lt_details*
        *append LS_DETAILS to LT_DETAILS.*
        *LO_ND_DETAILS->BIND_TABLE(*
        *NEW_ITEMS = LT_DETAILS ).*
    even though the above code will have the selected value, the SELECTIONS MADE will be initialize.
    you need to bind it explicitly.
    you have to create an element and bind the DDI values for adding an row as SARAVANAN said.
    or i guess you can continue with you code but need to use SET LEAD to display the correct SELECTIONS MADE
    loop at LT_DETAILS into LS_DETAILS.
          LV_TABIX = SY-TABIX.
          LR_ELEMENT = LO_ND_DETAILS->GET_ELEMENT( LV_TABIX ).
          WD_NODE = LR_ELEMENT->GET_CHILD_NODE( 'ACTIVITY_TYPES' ).
          WD_NODE->BIND_TABLE( NEW_ITEMS =  LT_ACTIVITY_TYPES ). " data for dropdown
    *" try to set the desired value in the DDI when you have multiple values using SET LEAD*
        endloop.

  • JTable with JButton Cell renderer

    How can I get buttons (JButtons) to "depress" properly in a JTable when using them as the cell renderer for a specific column in a JTable? Currently when pressing any button in the column, there is no change in the visible state of the button, i.e. it doesn't change color to create impression of depression.

    Is the [problem not the fact that the JTable cell renderers merely rubberstamp each cell with the appropriate display, i.e. the actual component in the cell is not an actual button (just looks like one)? If this is the case, then the same problem will persis with a JToggleButton as well won't it?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • JTable with custom cell for folding and unfolding rows

    Hi,
    I am trying to implement a JTable, whereas one of the columns is a custom component, which has a small + in the right upper corner.
    When you push this + the JTable should unfold other rows, giving more detail on the current row.
    So something like this :
    |--------------------------------|
    |   <some-string>              + |
    |--------------------------------|Drawing this custom component for the column is no problem but I am having trouble implementing the MouseMotionListener events over this.
    If I add a mouseMotionListener to the JTable, I am able to forward these events to my custom class which draws this custom component.
    But off course the X and Y coordinates of this MouseEvent are not mapped into the grid of my custom component, which poses my question.
    How can I attach to each cell of this custom column of my JTable, a listener as to implement some mouseover and mouseclick stuff ?
    In case this post is not all that clear, I will try to add a demo showing my problem.
    Kind regards,
    Wim.

    You're reinventing a wheel that's been done a few times. One example is JTreeTable (http://community.java.net/javadesktop/) but there are others.

  • JTable with JComboBox cells

    Hi all,
    When I make the JComboBox(es) become the cell of the JTable, the list of JComboBox is not expanded as the way a JComboBox behaves when you click on the arrow to see the whole list. I think the JComboBox is not receiving the mouse click event. Another way to say, something keeps the JComboBox from receiving the mouse click.
    Has anybody experienced this scenario?
    Frank.

    Is the table cell editable? If it isn't, that is your problem. Enable cell editing for that cell(s).
    Stephen

  • JTable with Labeles cells

    Is it possible to create Table where each cell
    will have permanent label (its number) together with an editable text?

    Yes we can have it like that
    for that u need to create a panel with one label and textbox in it
    and renderer that column with this panel

  • Table with Linktoaction cell editor VS ALV with Link to action cell editor

    Hi,
    i am replacing table UI with ALV, i am encountering series of problems one of them is below.
    when i click on linktoaction cell in table i can see wdevent has context_element which is element reference, which is being used in action handler to perform some logic...
    however when i replace with alv where i displayed one column with link to action cells using CL_SALV_WD_UIE_LINK_TO_ACTION class, however when i click on any particular cell i only get information related to that cell like column name, attribute name, value and position.
    however as i said i need context element reference to work with which is not coming with alv.
    please suggest.

    yes, that is right, you have to get the context element from the node based on the Index you get.

  • Help!!! JTable cell editor problem...

    I am having a problem with table cell editors.
    The problem is that when I click on another component
    in the frame (out side of the JTable) the cell editors's
    stopCellEditing() is not called so I get a JTable with a cell
    editor in editing mode.
    Any help?
    Thanks a lot

    It is difficult to tell what happens with FocusEvents when you are actually editing a cell and the editor is "up". I am experiencing different difficulties with the same root issue. I think the problem here is that the Java Focus Manager is consuming the focus event without propagating the event to any of the JTable components (CellEditor or JTable). I am not sure if this is exactly the case but I haven't been able to trap focus events in the Editors, Renderers or JTable anywhere. If the editor is not "up" then event handling seems to be fairly normal but when you are actually editing a cell it becomes tricky.
    However, this is a problem I fixed by placing a FocusGained event handler on the other (non JTable) component and then manually stopping editing on the JTable. In other words in the JFrame (or whatever component you are using) I added a FocusListener to the non JTable component and inside of FocusGanied() I execute:
    public void focusGained(FocusEvent e){
    table.getCellEditor().stopEditing();
    table.removeEditor();
    You could, of course, use cancelEditing() as well. You'll probably want to wrap the code with some robustness as follows to ensure that you don't get trapped by wierdness.
    public void focusGained(FocusEvent e){
    if (table.isEditing() && table.getCellEditor() != null){
    table.getCellEditor().stopEditing();
    table.removeEditor();
    This is probably not the only way to solve the problem but it was the way that worked when I encountered that issue.

  • I am really stuck with JCheckBox using it as a JTable cell editor...

    i need to focus next table cell, when user press a key on JcheckBox used in JTable as a cell editor.
    Especially i need to bind "ENTER" key with this action. I tried to addKeyListener do checkbox, tried to add action into input maps of jatble, and also to input map of checkbox. But really nothing works. Please help....
    Mathew, HSIGP

    and yes your code works well with any key, but when i want to assign something to "ENTER", it doesnt work. F.ex. if i assign something to "A" key
    like>
    InputMap m=table.getInputMap(WHEN_ANCETSTOR...);
    m.put(KeyStroke.get("A"),m.get(KeyStroke.get("TAB"));
    it works fine, and when i press "a" key it work as a "tab" key in table.
    But when i am doing same with "enter" instead of "a" it doesnt work.
    btw. there is action "actionselectNextCollumn..." assigned by default to enter
    why??

  • JTable custom cell editor losing focus

    This is a followup to Re: Tutorial on AWT/Swing control flow wherein I ask for pointers to help me understand the source of focus-loss behaviour in my JTable's custom cell editor.
    I have done some more investigations and it turns out that the focus loss is a more general problem with custom cell editors which call other windows. Even the color-picker demo in the JTable tutorial at http://download.oracle.com/javase/tutorial/uiswing/examples/components/index.html#TableDialogEditDemo has this problem, IF you add a text field or two to the layout BEFORE the table. The only reason the table in the demo doesn't lose the focus when the color-picker comes out is because the table is the only thing in the window!
    Here is the demo code, augmented with two text fields, which are admittedly ugly here but which serve the desired purpose:
    * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    *   - Redistributions of source code must retain the above copyright
    *     notice, this list of conditions and the following disclaimer.
    *   - Redistributions in binary form must reproduce the above copyright
    *     notice, this list of conditions and the following disclaimer in the
    *     documentation and/or other materials provided with the distribution.
    *   - Neither the name of Oracle or the names of its
    *     contributors may be used to endorse or promote products derived
    *     from this software without specific prior written permission.
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class TableDialogEditDemo extends JPanel {
        public class ColorEditor extends AbstractCellEditor
                implements TableCellEditor,
                ActionListener {
            Color currentColor;
            JButton button;
            JColorChooser colorChooser;
            JDialog dialog;
            protected static final String EDIT = "edit";
            public ColorEditor() {
                //Set up the editor (from the table's point of view), which is a button.
                //This button brings up the color chooser dialog, which is the editor from the user's point of view.
                button = new JButton();
                button.setActionCommand(EDIT);
                button.addActionListener(this);
                button.setBorderPainted(false);
                //Set up the dialog that the button brings up.
                colorChooser = new JColorChooser();
                dialog = JColorChooser.createDialog(button, "Pick a Color", true,  //modal
                        colorChooser, this,  //OK button handler
                        null); //no CANCEL button handler
             * Handles events from the editor button and from the dialog's OK button.
            public void actionPerformed(ActionEvent e) {
                if (EDIT.equals(e.getActionCommand())) {
                    //The user has clicked the cell, so bring up the dialog.
                    button.setBackground(currentColor);
                    colorChooser.setColor(currentColor);
                    dialog.setVisible(true);
                    //Make the renderer reappear.
                    fireEditingStopped();
                } else { //User pressed dialog's "OK" button
                    currentColor = colorChooser.getColor();
            public Object getCellEditorValue() {
                return currentColor;
            public Component getTableCellEditorComponent(JTable table,
                                                         Object value,
                                                         boolean isSelected,
                                                         int row,
                                                         int column) {
                currentColor = (Color) value;
                return button;
        public class ColorRenderer extends JLabel
                implements TableCellRenderer {
            Border unselectedBorder = null;
            Border selectedBorder = null;
            boolean isBordered = true;
            public ColorRenderer(boolean isBordered) {
                this.isBordered = isBordered;
                setOpaque(true);
            public Component getTableCellRendererComponent(
                    JTable table, Object color,
                    boolean isSelected, boolean hasFocus,
                    int row, int column) {
                Color newColor = (Color) color;
                setBackground(newColor);
                if (isBordered) {
                    if (isSelected) {
                        if (selectedBorder == null) {
                            selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                                    table.getSelectionBackground());
                        setBorder(selectedBorder);
                    } else {
                        if (unselectedBorder == null) {
                            unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                                    table.getBackground());
                        setBorder(unselectedBorder);
                return this;
        public TableDialogEditDemo() {
            super(new GridLayout());
            JTextField tf1 = new JTextField("tf1");
            add(tf1);
            JTextField tf2 = new JTextField("tf2");
            add(tf2);
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            table.setFillsViewportHeight(true);
            JScrollPane scrollPane = new JScrollPane(table);
            table.setDefaultRenderer(Color.class,
                    new ColorRenderer(true));
            table.setDefaultEditor(Color.class,
                    new ColorEditor());
            add(scrollPane);
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"First Name",
                    "Favorite Color",
                    "Sport",
                    "# of Years",
                    "Vegetarian"};
            private Object[][] data = {
                    {"Mary", new Color(153, 0, 153),
                            "Snowboarding", new Integer(5), new Boolean(false)},
                    {"Alison", new Color(51, 51, 153),
                            "Rowing", new Integer(3), new Boolean(true)},
                    {"Kathy", new Color(51, 102, 51),
                            "Knitting", new Integer(2), new Boolean(false)},
                    {"Sharon", Color.red,
                            "Speed reading", new Integer(20), new Boolean(true)},
                    {"Philip", Color.pink,
                            "Pool", new Integer(10), new Boolean(false)}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                if (col < 1) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("TableDialogEditDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new TableDialogEditDemo();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }When you come back from choosing a color, tf1 is given the focus, instead of the table. This is because bringing the color picker window to the front causes a focus lost event for the cell editor component; it's temporary, as it should be, so why on earth is the system losing track of who has focus in the window??
    I see the following in Window#getMostRecentFocusOwner():
      public Component getMostRecentFocusOwner()
        if (isFocused())
          return getFocusOwner();
        else
          Component mostRecent =
            KeyboardFocusManager.getMostRecentFocusOwner(this);
          if (mostRecent != null)
            return mostRecent;
          else
            return (isFocusableWindow())
                   ? getFocusTraversalPolicy().getInitialComponent(this)
                   : null;
      }My app has a custom focus traversal policy, so I'm able to see who is being called, and indeed, getInitialComponent() is being called. Clearly, the KeyboardFocusManager is actually losing track of the fact that the table was focussed at the point where control was transferred to the color picker! This strikes me as completely unreasonable, especially since, as noted, this is a temporary focus loss event, not a permanent one.
    I'd be grateful for any wisdom in solving this, since similar behaviour to this little demo -- without focus loss, naturally -- is an essential part of my application.

    Looks like it is because the 'restore-focus-to-previous-after-modal-dialog-close' is in a later event than when the control returns to the action performed (which I guess makes sense: it continues the action event handler and the focus events are handled later, but I needed two chained invoke laters so it might also be that the OS events comes later).
    The following works for me (in the actionPerformed edited):
               // create the dialog here so it is correctly parented
               // (otherwise sometimes OK button not correctly the default button)
               dialog = JColorChooser.createDialog(button, "Pick a Color", true,  //modal
                            colorChooser, this,  //OK button handler
                            null); //no CANCEL button handler
                    //The user has clicked the cell, so bring up the dialog.
                    button.setBackground(currentColor);
                    colorChooser.setColor(currentColor);
                    button.addFocusListener(new FocusListener() {
                        @Override
                        public void focusLost(FocusEvent e) {}
                        @Override
                        public void focusGained(FocusEvent e) {
                            // dialog closed and focus restored
                            button.removeFocusListener(this);
                            fireEditingStopped();
                    dialog.setVisible(true);but a simpler request might be better (althoug I still need an invoke later):
    // rest as before except the FocusListener
                    dialog.setVisible(true);
                    button.requestFocusInWindow();
                    EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            fireEditingStopped();
                    });And a quick fix to the renderer so you can actualy see the focus on it:
                    if(hasFocus) {
                        Border border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
                        setBorder(BorderFactory.createCompoundBorder(
                                border, BorderFactory.createMatteBorder(1, 4, 1, 4,
                                        ((MatteBorder) getBorder()).getMatteColor())));
                    }

Maybe you are looking for

  • MSS error while trying to access Adobe forms

    Hi all We are using EP 7 sp14. Delpoyed ESS/MSS BP SP 14. while trying to access certain functionalities in MSS which make use if standerd Adobe interactive forme through portal its coming up with the following error. com.sap.engine.services.webservi

  • IPod as a disk drive

    Sorry if this has been covered before, I've not had a lot of time to search the forums, and wanted a quick response! I've set my iPod to be treated as a disk drive and I can explore it with no problems via Windows Explorer. Rather than using iTunes t

  • Installing XP on mac mini without bootcamp

    My apple mac mini was divided into three partitions (Macintosh, Vista and Linux) by my brother without using boot camp assistant (he used some other utility I think), and all these OSs work. Is it possible to install XP over the Vista partition, by i

  • Activations unavailable?

    i tried to update my development iphone with sdk 7. when i get to the point of activating it in itunes, i get a message saying that activations are not available at this time. unfortunately, this means my development device is useless. any ideas how

  • HT4623 how can i get ios 7.1 beta 2?

    how can i get ios7.1 Beta 2 on my 5s?