JTable custom cell editor focus problem

Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

Hi I have created a JTable (using Java 1.4.2) and have three cell Editors, one is a JFormattedTextField, one is a JComboBox and one is a custom cell editor.
When I press tab I can select the cell with the JFormattedTextField and when I start typing the JFormattedTextField accepts my input and it is displayed in the cell. This is the type of behaviour I would like but it does not seem to work for my other 2 cell editors:
When I tab to the JComboBox cell I can see that the cell is selected but typing or using the arrow keys does not allow me to select a new value in the JComboBox. (I have also tried typing space or enter to activate the JComboBox whilst the cell is selected.) The only ways to select a new value at the moment is to first click on the cell with the mouse and then use the keyboard to select a new value. It is like the actual JComboBox is not receiving the focus? Does anyone know how to solve this problem?
I also seem to have the same problem with my custom cell editor. My custom editor is a JPanel which contains JFormattedTextField again I can tab to the cell and see that it is selected but to activate the JFormattedTextField I have to actually select it with the mouse.
I have been stuck on this for some time so if any one has any suggestions they would be much appreciated !

Similar Messages

  • JTable Custom Cell Editor "focus through keyboard" question (SSCCE included

    I was trying to use two components in a table cell. The first was JTextField and second the JButton. Everything works fine, except when it comes to editing the JTextfield using keyboard instead of mouse. When I use tab key to go to the custom cell, I can see that the focus is on the cell (as can be visible from background color). But when I try to edit the cell using F2 or directly entering text, nothing gets entered. If I use the mouse to go to particular cell, it works fine. Here is SSCCE. Try the following.
    1. Use mouse key to select first cell for editing. Edit the cell. Everything normal.
    2. Use the tab key to go to the first cell. Try to edit cell either by entering directly for after using F2. Can't get the typed text into the JTextfield.
    package com.ns;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class TextButtonCellFrame extends javax.swing.JFrame {
        // Variables declaration - do not modify
        private JScrollPane jScrollPane1;
        private JPanel testPanel;
        private JTable testTable;
        // End of variables declaration
        public TextButtonCellFrame() {
            initComponents();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            testPanel = new JPanel();
            jScrollPane1 = new JScrollPane();
            testTable = new JTable();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            testTable.setModel(new DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            testTable.setRowHeight(20);
            testTable.getColumnModel().getColumn(0).setCellRenderer(new MyTableCellRenderer());
            testTable.getColumnModel().getColumn(0).setCellEditor(new MyTableCellEditor());
            testTable.getColumnModel().getColumn(0).setPreferredWidth(200);
            jScrollPane1.setViewportView(testTable);
            testPanel.add(jScrollPane1);
            getContentPane().add(testPanel, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-496)/2, (screenSize.height-330)/2, 496, 330);
        }// </editor-fold>
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TextButtonCellFrame().setVisible(true);
        public class MyTableCellRenderer extends JPanel implements TableCellRenderer {
            Point point;
            JButton button1 = new JButton("Test 1");
            JTextField txtField = new JTextField();
            public MyTableCellRenderer() {
                setLayout(new BorderLayout());
                this.add(button1, BorderLayout.EAST);
                this.add(txtField,BorderLayout.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
                if (isSelected) {
                    txtField.setBackground(testTable.getSelectionBackground());
                    txtField.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
                else {
                    txtField.setBackground(testTable.getBackground());
                    txtField.setBorder(null);
                return this;
        public class MyTableCellEditor extends DefaultCellEditor
                                        implements ActionListener {
            JPanel panel = new JPanel();
            JButton button1 = new JButton ("Test 1");
            JTextField txtField = new JTextField();
            MyTableCellEditor() {
                super (new JTextField());
                button1.addActionListener(this);
                panel.setLayout(new BorderLayout());
                panel.add(button1, BorderLayout.EAST);
                panel.add(txtField,BorderLayout.CENTER);
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == button1)
                    JOptionPane.showMessageDialog(null, "Action One Successful");
            public Component getTableCellEditorComponent(JTable table, Object value,
                                        boolean isSelected, int row, int column) {
                txtField.requestFocusInWindow();
                return panel;
    }regards,
    nirvan.

    I don't know what's better:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.EventObject;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TextButtonCellFrame extends JFrame {
      JTable testTable = new JTable();
      public TextButtonCellFrame() {
        testTable.setModel(new DefaultTableModel(
          new Object [][] {
            {null, null, null, null},
            {null, null, null, null}
          new String [] { "1", "2", "3", "4" }
        testTable.setRowHeight(20);
        testTable.getColumnModel().getColumn(0).setCellRenderer(
          new MyTableCellRenderer());
        testTable.getColumnModel().getColumn(0).setCellEditor(
          new MyTableCellEditor(new JTextField()));
        testTable.getColumnModel().getColumn(0).setPreferredWidth(200);
        getContentPane().add(new JScrollPane(testTable));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(480,320);
        setLocationRelativeTo(null);
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TextButtonCellFrame().setVisible(true);
      public class MyTableCellRenderer extends JPanel
                    implements TableCellRenderer {
        JButton button1 = new JButton("Test 1");
        JTextField txtField = new JTextField();
        public MyTableCellRenderer() {
          setLayout(new BorderLayout());
          this.add(button1, BorderLayout.EAST);
          this.add(txtField,BorderLayout.CENTER);
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
          if (isSelected) {
            txtField.setBackground(testTable.getSelectionBackground());
            txtField.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
          } else {
            txtField.setBackground(testTable.getBackground());
            txtField.setBorder(null);
          txtField.setText(value==null?"":value.toString());
          return this;
      public class MyTableCellEditor extends DefaultCellEditor
                      implements ActionListener {
        JPanel panel = new JPanel(new BorderLayout());
        JButton button1 = new JButton ("Test 1");
        JTextField txtField; // = new JTextField();
        MyTableCellEditor(JTextField txtField) {
          super (txtField);
          this.txtField = txtField;
          button1.addActionListener(this);
          panel.add(button1, BorderLayout.EAST);
          panel.add(txtField,BorderLayout.CENTER);
        public void actionPerformed(ActionEvent e) {
          if (e.getSource() == button1)
            JOptionPane.showMessageDialog(null, "Action One Successful");
        public Component getTableCellEditorComponent(JTable table, Object value,
                      boolean isSelected, int row, int column) {
          txtField.setText(value==null?"":value.toString());
          SwingUtilities.invokeLater(new Runnable() {
            public void run() {
              txtField.requestFocusInWindow();
          return panel;
    }

  • 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())));
                    }

  • JTable - Custom cell editor lossing commit

    Hello,
    I have a custom cell editor and a default renderer assigned to a specific cell in my table...
    I have the following problem :
    If i change the value of cell 'c1' from value 'v1' to 'v2' and press enter and go to another cell the value in 'c1' is rendered correctly as 'v2'
    Hoever if i change the value of cell 'c1' from 'v1' to 'v2' and simply click over to another cell the value in 'c1' stays rendered as 'v1'
    Question : Is there ANY way to mimic the behavior of the user pressing enter in my custom cell editor when a user simply selects another cell, i guess on loss of focus or something..
    This is the last problem i have on the current project i am on and its very annoying.
    Thanks in advance, any help appreciated..
    -Alan

    I have the same problem using a custom Date/Time Picker Object (which extends JComboBox) as an editor within a table cell. For simplicity sake, I am posting code using only the base editable JComboBox, but it exhibits the same symptoms. If you enter a value in the TextField portion of the ComboBox and Tab, your value remains the same. If you enter a value in the TextField portion of the ComboBox and click in another cell, the value returns to the previous value (before editing began).
    import java.awt.*;                                                  // BorderLayout
    import javax.swing.*;                                               // JTable, JFrame
    import javax.swing.table.*;                                         // DefaultTableModel
    public class Tester extends JFrame
      public static void main(String[] args)
        Tester test = new Tester();
      public Tester()
        String[] values = {"Test", "Values"};
        JComboBox combo = new JComboBox(values);
        combo.setEditable(true);
        DefaultCellEditor editor = new DefaultCellEditor(combo);
        JTable table = new JTable(2, 3);
        table.getColumn(table.getColumnName(0)).setCellEditor(editor);
        JScrollPane scroll = new JScrollPane(table);
        getContentPane().add(scroll, BorderLayout.CENTER);
        pack();
        setVisible(true);
    }

  • JTable & custom cell editor

    Hello everyone,
    what is the correct way of writing a custom cell editor for a JTable? I followed the example in the Java tutorial ([How to use tables|http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editor]), but the result is a bit weird. The code I have is the following:
        private class NumericCellEditor extends AbstractCellEditor implements TableCellEditor {
            NumericFTField field = new NumericFTField(threeDecimalsFormat, 3, null, 1);
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int col) {
                field.setValue(value);
                return field;
            public Object getCellEditorValue() {
                return field.getValue();
            @Override
            public boolean stopCellEditing() {
                if (((NumericFTField)field).verifyDouble()) {
                    field.setBorder(new EmptyBorder(0, 0, 0, 0));
                    fireEditingStopped();
                    return true;
                } else {
                    field.setBorder(BorderFactory.createLineBorder(Color.red));
                    return false;
        }where the NumericFTField is a class derived from JFormattedTextField that only allows digits, decimal separator, minus and 'E' to be inserted, and it monitors clipboard operations. verifyDouble() is a method of the NumericFTField class that verifies whether the current input can be parsed to a double and whether it satisfies everything it should. This is then used in
    ((TableColumn)jTblSpecs.getColumnModel().getColumn(1)).setCellEditor(new NumericCellEditor());The NumericFTField class works great, I use it also in place of a JTextFields, so I'd say there is nothing wrong with it.
    After I click in a cell (single click), it behaves a little different that the default cell editor: the cell is not highlighted, but it immediately jumps to the editing state (why???). I, indeed, can insert the allowed characters only. When I click in a cell, do some editing and press Enter, the cell's content gets validated. If it is invalid, stopCellEditing() method does its magic; if it is valid, the caret disappears and everything SEEMS okay. However, if I started typing at this point, the cell reverts to the editing state, but now I am able to enter any character I want. It truly looks like the cell editor is now some other component, not the original NumericFTField one. What is going on here?
    It would be great is someone could provide a short schematic source of a custom cell editor class that would work exactly as the JTable's default one except it would only permit digits and so on. It doesn't have to be anything fancy, just a "skeleton" of the class with comments like "input verification here" etc.
    I am sorry for any lack of clarity, but I am still a Java newbie.
    Any help would be much appreciated.
    Best regards,
    vt

    Hi,
    I am also facing the same problem. In addition to what you have specified, my requirement is to be able to select multiple rows for deletion. But, the very first row selected using mouse is not visible as selected though its selected. The other rows are visible as selected.
    If you can use any JDK version, start using JDK1.6. You will not be facing this problem. There were so many changes done for swings from JDK 1.4 to 1.6. But, I have to strictly use JDK1.4, but could not find any workaround for this problem.
    It would be great if anyone can help me out in this issue to get workaround for this problem.

  • JTable Custom Cell Editor: how to get value?

    I have some custom cell renderers and editor. One of my custom cell editor is a text field that can popup a separat gui for easier data selection. As this text field alone with the popup gui works great, when i use this field in my custom jtable cell editor, the gui selected value is never displayed in the table cell. it just shows the old value.?

    Well, here's how I do it. I'm very new to Swing so I'm, not sure if this is the best way. If you find a better way, please repost on this message.
    My cell editor is a JPanel with a JTextfield in it. I make sure that the JTextfield will have default focus when the JPanel is focused.
    In the CellEditor, I add a KeyListener to the JTextField so that when the user hits enter, it fires the stopEditing. I then add a function to CellEditor that returns what's in the JTextField.
    In the code, m_value is the JTextField. You want to add MyKeyAdapter to the JTextField. Viola, it works!
          * This private class reads in an enter key.
         class MyKeyAdapter extends KeyAdapter {
              public void keyPressed(KeyEvent e) {
                   if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                        stopCellEditing();
          * Returns the value of the editor
          * @return the value of the editor
         public String getValue() {
              return m_value.getText();

  • 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.

  • JTable custom cell renderer and editor breaks row sorting

    Hello Forum,
    I have a JTable on which I set setAutoCreateRowSorter(true); I then hook up a custom cell editor and renderer for the Date class.
    this.tblLeden.setDefaultRenderer(Date.class, new DateCellEditor());
    this.tblLeden.setDefaultEditor(Date.class, new DateCellEditor());
    The sorting for that particular row then breaks, it works fine for every other row. How do I fix this? Just directions where to look would be great too.
    Here is my code for the renderer/editor:
    (btw this is probably not the best way to do this so any suggestions for optimizing are great too)
    import java.awt.Component;
    import java.util.Date;
    import java.util.EventObject;
    import java.util.HashMap;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import com.toedter.calendar.JDateChooser;
    public class DateCellEditor extends JDateChooser implements TableCellRenderer, TableCellEditor
      private static final long serialVersionUID = -5073758499524392257L;
      private final Vector<CellEditorListener> listeners = new Vector<CellEditorListener>();
      // oops.. lingering objects problem when rows are deleted..
      private final HashMap<Integer, JDateChooser> components = new HashMap<Integer, JDateChooser>();
      @Override
      public final Component getTableCellRendererComponent(final JTable table,
          final Object value, final boolean isSelected, final boolean hasFocus,
          final int row, final int col)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final Component getTableCellEditorComponent(final JTable table,
          final Object value, final boolean isSelected, final int row,
          final int column)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final void addCellEditorListener(final CellEditorListener arg0)
        this.listeners.addElement(arg0);
      @Override
      public final void removeCellEditorListener(final CellEditorListener arg0)
        this.listeners.removeElement(arg0);
      @Override
      public final void cancelCellEditing()
        return;
      @Override
      public final Object getCellEditorValue()
        return null;
      @Override
      public final boolean isCellEditable(final EventObject arg0)
        return true;
      @Override
      public final boolean shouldSelectCell(final EventObject arg0)
        return true;
      @Override
      public final boolean stopCellEditing()
        return true;
    }

    This seems to work:
    import java.awt.Component;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.sql.Date;
    import java.util.EventObject;
    import java.util.HashMap;
    import java.util.Vector;
    import javax.swing.JTable;
    import javax.swing.event.CellEditorListener;
    import javax.swing.event.ChangeEvent;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import com.toedter.calendar.JDateChooser;
    public class DateCellEditor implements TableCellRenderer, TableCellEditor, PropertyChangeListener
      private static final long serialVersionUID = -5073758499524392257L;
      private final Vector<CellEditorListener> listeners = new Vector<CellEditorListener>();
      // oops.. lingering objects problem when rows are deleted..
      private final HashMap<Integer, JDateChooser> components = new HashMap<Integer, JDateChooser>();
      private Date storedValue = null;
      @Override
      public final Component getTableCellRendererComponent(final JTable table,
          final Object value, final boolean isSelected, final boolean hasFocus,
          final int row, final int col)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          temp.addPropertyChangeListener("date", this);
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final Component getTableCellEditorComponent(final JTable table,
          final Object value, final boolean isSelected, final int row,
          final int column)
        JDateChooser temp = this.components.get(Integer.valueOf(row));
        if (temp == null)
          temp = new JDateChooser();
          temp.addPropertyChangeListener("date", this);
          this.components.put(Integer.valueOf(row), temp);
        temp.setDate((Date) value);
        return temp;
      @Override
      public final void addCellEditorListener(final CellEditorListener arg0)
        this.listeners.addElement(arg0);
      @Override
      public final void removeCellEditorListener(final CellEditorListener arg0)
        this.listeners.removeElement(arg0);
      @Override
      public final void cancelCellEditing()
        return;
      @Override
      public final Object getCellEditorValue()
        return this.storedValue;
      @Override
      public final boolean isCellEditable(final EventObject arg0)
        return true;
      @Override
      public final boolean shouldSelectCell(final EventObject arg0)
        return true;
      @Override
      public final boolean stopCellEditing()
        return true;
      @Override
      public final void propertyChange(final PropertyChangeEvent arg0)
        if (((JDateChooser) arg0.getSource()).getDate() == null)
          return;
        this.storedValue = new Date(((JDateChooser) arg0.getSource()).getDate().getTime());
        ChangeEvent event = new ChangeEvent(arg0.getSource());
        for (int i = 0; i < this.listeners.size(); i++)
          this.listeners.elementAt(i).editingStopped(event);
    }

  • Positioning custom cell editors

    I've got a custom cell editor that Im using to edit the cells of my JTable.
    I cant use a DefaultCellEditor, as my editor will contain a JTree.
    When I display the editor, I want to position it along-side the cell which was selected for editing.
    I can see methods in JTable to find the row/column at a given Point, but cant find any to get the location of a chosen row/column.
    Does anyone know if there is a way to do this?

    Here is some code that I used with a lot of debug messages. My editor is a table and the movement references was because the table could be off the parent table panel. If it was too far to the right, I wanted to move my popup table to the left to compensate.
         * Return the editor component to the table
         * @param table container for the editor
         * @param value value from the model
         * @param isSelected is the cell selected (has focus)
         * @param row of the cell
         * @param column of the cell
         * @return aLabel is used to provide visual feedback that the editor is
         * working
        public Component getTableCellEditorComponent(
            JTable table, Object value, boolean isSelected, int row, int column)
            logger.debug("PicklistEditor: getTableCellEditorComponent.value(" + value + ")");
            editingRow = row;
            editingColumn = column;
            dataEntryTable = table;
            dataEntryTable.setSurrendersFocusOnKeystroke(true);
            Rectangle tableRectangle = dataEntryTable.getBounds();
            int tableRightEdge = tableRectangle.x + tableRectangle.width;
            Point p = dataEntryTable.getLocationOnScreen();
            Rectangle r = dataEntryTable.getCellRect(row, column, true);
            Rectangle picklistRectangle = picklistFrame.getBounds();
            logger.debug("PicklistEditor: table.getBounds() = " + table.getBounds());
            logger.debug("PicklistEditor: tableRightEdge = " + tableRightEdge);
            logger.debug("PicklistEditor: picklistFrame.getBounds() = " + picklistFrame.getBounds());
            picklistFrame.setLocation(p.x + r.x, p.y + r.y + r.height);
            picklistFrame.setVisible(true);
            logger.debug(
                "PicklistEditor: picklistFrame.getLocationOnScreen() = " +
                picklistFrame.getLocationOnScreen());
            int picklistRightEdge = picklistFrame.getLocationOnScreen().x + picklistRectangle.width;
            int moveRightAmount = 0;
            if (picklistRightEdge > tableRightEdge)
                moveRightAmount = picklistRightEdge - tableRightEdge;
                picklistFrame.setLocation((p.x + r.x) - moveRightAmount, p.y + r.y + r.height);
            logger.debug("PicklistEditor: picklistRightEdge = " + picklistRightEdge);
            logger.debug("PicklistEditor: moveRightAmount = " + moveRightAmount);
            javax.swing.SwingUtilities.invokeLater(
                new Runnable()
                public void run()
                    editField.requestFocusInWindow();
            aLabel.setText("Editing...");
            logger.debug("PicklistEditor: editPanel.getBounds(" + editPanel.getBounds() + ")");
            logger.debug("PicklistEditor: editInputPanel.getBounds(" + editInputPanel.getBounds() +
            logger.debug("PicklistEditor: acceptEditFieldButton.getBounds(" +
                acceptEditFieldButton.getBounds() + ")");
            logger.debug("PicklistEditor: picklistScrollPane.getBounds(" +
                picklistScrollPane.getBounds() + ")");
            return aLabel;
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Stopcellediting removes my custom cell editor

    Hi Gurus,
    Please look at the following where I am using stopcellediting with my custom editor. Problem is when I use stopcellediting, it removes the cell editor from the table, so in result any function I want to do in the cell editor doesnt get executed anymore. I tried setcelleditor right after stopcellediting but did not fix.
    For example if user types anything else than number I want to check and when it reaches 10 characters I want to add new blank record, but stopCellEditing does not let me do it, and I have to stopCellEditing in certain conditions (I did not include those conditions here) eg if user clicks tab or delete or etc.
    Pleas HELP
    Thanks,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    public class TableEdit extends JFrame
         TableEdit()
              JTable table = new JTable(5,5);
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollpane = new JScrollPane(table);
              getContentPane().add(scrollpane);
              //  Use a custom editor
              TableCellEditor fce = new FiveCharacterEditor();
              table.setDefaultEditor(Object.class, fce);
        // Editor class
        class MyNumberEditor extends javax.swing.AbstractCellEditor implements TableCellEditor
            private JTextField editor;
            public MyNumberEditor()
                super();
                editor = new JTextField();
                try
                    editor.addKeyListener(new java.awt.event.KeyAdapter() {
                        public void keyTyped(KeyEvent e)
                            super.keyTyped(e);
                            editorKeyTyped(e, 0);
                        public void keyReleased(KeyEvent e)
                            super.keyReleased(e);
                            editorKeyTyped(e, 1);
                } catch (Exception e){}
            public Object getCellEditorValue()
                return editor.getText();
            public Component getTableCellEditorComponent(JTable table,
                    Object value, boolean isSelected, int row, int column)
                if(value instanceof String)
                    editor.setText((String)value);
                return editor;
            private void editorKeyTyped(KeyEvent e, int event)
    System.out.println("editorKeyTyped.................: "+e.getKeyCode()+" - "+e.getKeyChar());
                if(event == 1)
                    if(jTable.isEditing())
                        stopCellEditing();
    //                    tableColumn.setCellEditor(this);
                    int numbers = 0;
                    int rows = jTable.getRowCount();
                    for(int i = 0; i < rows; i++)
                        String number = ((String)jTable.getValueAt(i, 0)).trim();
                        if(number.length() > 0)
                            numbers++;
                if(event == 0 && editor.getText().trim().length() == 9 && e.getKeyChar() != 8)
                    addBlankRecord();
         public static void main(String [] args)
              JFrame frame = new TableEdit();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

    hi camikr
    Thanks again for your help.
    here is the sample program, i tried setClickCountToStart. it still doesnt show the cursor, if i dont click.
    Also when I type the value in the first cell eg, i have to press tab TWICE to get to the next cell. or if it has error eg not 10 digits and then I fix it then again i have press TAB twice to get to next field
    How can display the cursor when I click or use tab to next field, and how to use one tab only to get to the next field.
    Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.text.*;
    public class MyTable2 extends JFrame
        JTable jTable;
        DefaultTableModel tm;
        MyTable2()
            jTable = null;
            tm = null;
            JButton dumy = new JButton("dummy button");
            JPanel panel = new JPanel();
            panel.setLayout(new BorderLayout());
            tm = new DefaultTableModel(1, 1);
            jTable = new JTable(tm);
            jTable.setPreferredScrollableViewportSize(jTable.getPreferredSize());
            JScrollPane scrollpane = new JScrollPane(jTable);
            scrollpane.setPreferredSize(new Dimension(100,200));
            panel.add(dumy, "North");
            panel.add(scrollpane, "South");
            JTextField field = new JTextField();
            TableCellEditor fce = new MyNumberEditor(field);
            TableColumn col = null;
            col = jTable.getColumn(jTable.getColumnName(0));
            col.setCellEditor(fce);
            getContentPane().add(panel);
        class MyNumberEditor extends DefaultCellEditor
            String allowedValues = "0123456789";
            int allowedLength = 10;
            public MyNumberEditor(JTextField field)
                super(field);
                setClickCountToStart(0);
            public boolean stopCellEditing()
                try
                    String editingValue = (String)getCellEditorValue();
                    if(editingValue.length() > 0 && editingValue.length() != allowedLength)
                        setErrorMessage("Please enter 10 digits.");
                        return false;
                    if(editingValue.length() == allowedLength)
                        for(int i = 0; i < allowedLength; i++)
                            String val = editingValue.substring(i,i+1);
                            if(allowedValues.indexOf(val) == -1)
                                setErrorMessage("Please enter digits only.");
                                return false;
                } catch(ClassCastException exception)
                    return false;
                boolean stopped = super.stopCellEditing();
                tm.addRow(new Object[]{""});
                return stopped;
            public void setErrorMessage(String message)
                JTextField textField = (JTextField)getComponent();
                textField.setBorder(new LineBorder(Color.red));
                textField.selectAll();
                textField.requestFocus();
                JOptionPane.showMessageDialog(null,
                                              message, "Error",JOptionPane.ERROR_MESSAGE);
            public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column) {
                Component c = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                ((JComponent)c).setBorder(new LineBorder(Color.black,1));
                return c;
        public static void main(String args[])
            JFrame frame = new MyTable2();
            frame.setDefaultCloseOperation(3);
            frame.pack();
            frame.setVisible(true);
    }

  • Overriding double click in JTable custom cell

    I have a JTable where I reset the custom cells to become editable on a single click instead if a double using:
    ((DefaultCellEditor)table.getDefaultEditor(String.class)).setClickCountToStart(1);
    Now what I need to do is display a JPopupMenu click a cell is double clicked. This works on cells that are not editable but the problem is that the user needs the popup dialog to display info for the cells that are editable.
    I have used the basic way to implement a double click on a certain column (in this case my third column):
    public void mouseClicked(MouseEvent e){
                   if (e.getClickCount() == 2 && table.getSelectedColumn() == 2 ){
                        popupMenu.show( e.getComponent(),
    e.getX(), e.getY() );
    But when double clicking, nothing happens.
    Anyone have any idea to implement this or over-ride an editable cell?
    Thanks,
    Chris

    This still says <identifier> expect, how can I resove this please? Then you still have something wrong with your code. Since you didn't post your code how are we supposed to help?
    The proper way to ask a question is to include your demo code that trys to illustrate the problem. Something like the following:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TableRightClick extends JFrame
         public TableRightClick()
              JTable table = new JTable(10, 5);
              table.addMouseListener( new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        if ( SwingUtilities.isRightMouseButton(e) )
    //                    if (e.isPopupTrigger())
                             JTable source = (JTable)e.getSource();
                             int row = source.rowAtPoint( e.getPoint() );
                             int column = source.columnAtPoint( e.getPoint() );
                             System.out.println(column);
                             source.changeSelection(row, column, false, false);
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              getContentPane().add( new JScrollPane(table) );
         public static void main(String[] args)
              TableRightClick frame = new TableRightClick();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
    }

  • JComboBox cell editor *Listener problem

    Hi all,
    I've setup a TreeTable with a JComboBox as a CellEditor for the second column.
    Everything works just fine, except for event handling on a column with a JComboBox as cell editor.
    In my case, the second column of the TreeTable represents the state of the activities. This state can be changed either programmatically or by user input. That is, my application can automatically change the state for some reason, or the user can select a new state for a particular activity with the mouse.
    What I need to achieve is to capture events generated only from the user.
    I've tried different solutions, adding ActionListener or ItemListener to the CellEditor, but they all capture events generated by the application in addition to those generated by the user of the application.
    Can someone please give me some advice in this matter?
    Xserty

    What I need to achieve is to capture events generated only from the user.If you called the JComboBox's dataModel.setSelectedItem method yourself, no event will be fired!Unfortunately, I'm not able to update the dataModel (directly) myself.
    I'm currently using the Creating TreeTables: Part 3; here's how it kinda works: my JTreeTable extends JTable. The JTreeTable has a model: TreeTableModel extends DefaultTreeModel implements InterfaceJTreeTableModel. In this model there are two methods implemented as following:
    public Object getValueAt(Object pParentNode, int pColumn) {
      MutableActivityNode activityNode = (MutableActivityNode) pParentNode;
      try {
        switch (pColumn) {
          case 0 :
            return activityNode.getName();
          case 1 :
            return activityNode.getState();
          case 2 :
            return new Boolean(activityNode.isMonitored());
          default :
            // do something
      } catch (SecurityException se) {
        // do something
      return null;
    public void setValueAt(Object pValue, Object pNode, int pColumn) {
      MutableActivityNode activityNode = (MutableActivityNode) pNode;
      try {
        switch (pColumn) {
          case 1 :
            activityNode.setState((String) pValue);
            break;
          case 2 :
            activityNode.setIsMonitored(((Boolean) pValue).booleanValue());
            break;
          default :
            // do something
      } catch (SecurityException se) {
        // do something
    }Once I create my JTreeTable (with a model), I set the editor of the second column of my JTreeTable to a JComboBoxCellEditor.
    As you may have noticed, all the information are stored in the node of the TreeTableModel and the information is displayed and set by the two methods above.
    Thank you anyways for the advice :))
    Have you any idea on how I could solve the problem in this case?
    Xserty

  • Default cell editor extending problem

    hello again,
    special thanks to camikr, who has helped me a lot in my problems.
    now I will like to know should I implement the default cell editor interface or extend the available class to solve my previous problem of validating table cells?
    which methods should I concentrate on? I will certainly work on is cell editable but kindly suggest me if I want to prevent the tab key from moving the focus to next cell without satisfying certain conditions, what events or methods should I concentrate. if I want the tab key to be blocked what action should I take?
    thanks
    Krishnakant.

    if I want to prevent the tab key from moving the focus to next cell
    without satisfying certain conditions, what events or methods should I concentrateYou where given a working example of this in your last posting:
    http://forum.java.sun.com/thread.jspa?threadID=642364&messageID=3786315
    The example only overrides two methods. Only one of the methods has validation logic. So I would think it would be obvious which method to concentrate on.

  • Event Handling in JTable Custom Cell Renderer

    I have a JLabel as a custom cell Renderer for a column. I want to handle mouse click event for the JLabel rendered in the cell.
    I tried adding the listener for the label in the custom cell renderer but it is not working. Any ideas how to handle this problem??
    Thanks
    S.Anand

    If you want to handle the selection of a tree node
    1) write a class like:
    public class TreePaneListener implements TreeSelectionListener {
    // TREE SELECTION LISTENER
    public void valueChanged(TreeSelectionEvent e) {
    JTree tree = (JTree)e.getSource();
    DefaultMutableTreeNode node = null;
    int count = 0;
    boolean doSomething = false;
    if(tree.getSelectionCount() > 1) {
         TreePath[] selection = tree.getSelectionPaths();
         int[] temp = new int[selection.length];
         for(int i =0; i < selection.length; i++) {
    // Check each node for selection
         node = (DefaultMutableTreeNode)selection.getLastPathComponent();
         if(node.getLevel()==2) {
    // Change this code to take the action desired
         doSomething = true;
    2) After creating the tree register the listener
    TreePaneListener handler = new TreePaneListener();
    tree.addTreeSelectionListener(handler);

  • JTable Custom Cell  Event handling

    Hi,
    I have a column in JTable as image which is rendered by using custom cell renderer. I want to handle action event for the cell...
    I tried adding actionPerformed event for the button using which the image is rendered but the event is not triggered....
    Can you please tell me how to proceed with this
    Thanks,
    S.Anand

    I'm assuming you want to know when the user has clicked on a particular cell in the table. If so, add a MouseListener to the table then implement a MouseListener or one of the Mouse...Adapter classes with the method:
    public void mouseClicked(MouseEvent e)
        Point p = e.getPoint();
        int row = table.rowAtPoint(p);
        int col = table.columnAtPoint(p);
        // now do something according to the cell that was clicked

Maybe you are looking for

  • I am trying to add a footer and Adobe Pro XI keeps crashing

    I am trying to add a footer to my document and Adobe Pro XI keeps crashing.  Any ideas?

  • Unable to download OS X Mavericks

    I have tried numerous times to download Mac OS X Mavericks, but nothing happens. Seems I am not the only one. I am on currently on Mac OS X 10.6.8

  • Call search help as seperately

    Hello, May I know if there is possible to call the popup window for search help directly, but not through the input field which uses the search help.Thank you very much! Best regards, Shumin

  • Simple read code from RS232

    Hi I want to read stream of bytes from rs232 connected to microcontroller which send data ,i 'm sure that data arrive proberely before the serial cable but the code have aproblem see it package myserial; import java.io.*; import java.util.*; import j

  • Module pool in table control wizared

    Hi I have created in module pool table control wizared created insert and delete rows in output. insert the data in table control the colume is not save. can u tell me the save the data in table control. pls tell me the flow of save button. after ins