Problems with JTable custom cell renderers

Hi All,
I'm having a bit of a problem writing a custom renderer for a JTable.
What seems to be happening is that the changes I apply in the renderer to the component are applied to ALL cells.
All I want to do is have a different background color for certain cells....
Ive derived from DefaultTableCellRenderer, so Im using its getTableCellRendererComponent to do most of the work.
So, Ive got something like this:
private class DirtyCacheRenderer extends DefaultTableCellRenderer
    public Component getTableCellRendererComponent(JTable table, Object value,
                          boolean isSelected, boolean hasFocus, int row, int column)
      // Modifies 'this'
      super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
      // If the row/column is 'dirty' (I.e - if I want 2 color it diferently)
      if(((EditableTableModel)table.getModel()).isDirty(row,column))
        // The column is dirty. Set the color accordingly:
        super.setBackground(DIRTY_COLOR);
      return this;
  }The effect is that as soon as ONE cell gets its color set above, all of the cells do!
Please help, its driving me mad!!!
D

I tried this and it worked. Tell me if it is OK for you.
import javax.swing.table.TableCellRenderer;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.JLabel;
public class testRenderer implements TableCellRenderer {
JLabel cell = new JLabel();
Color dirty = new Color(100,100,100);
Color clear = new Color(0,0,0);
public testRenderer() {
cell.setOpaque(true);
public Component getTableCellRendererComponent(JTable table,Object value,
boolean isSelected,boolean hasFocus, int row, int column) {
cell.setText(value.toString());
// The column is dirty. Set the color
if (row == column)     {
cell.setBackground(dirty);
} else {
cell.setBackground(table.getBackground());
return cell;
}

Similar Messages

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

  • A problem with JTable

    Hi !
    I have a problem with JTable - would like to use this component as a simple list of rows taken from a database : don't want to be able select or set a focus to a column - want only to be able select and set focus to a row ( just like in the menus). How to disable "focusability" for a cell with JTable ? Could You help me ?
    thnx in advance

    The Border is changed by the renderer, depending on whether the cell has focus or not. So you will need to create custom renderers without a Border. Something like:
    class NoBorderRenderer extends DefaultTableCellRenderer
         public Component getTableCellRendererComponent(
              JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
              super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              setBorder(null);
              return this;
    }

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

  • JTable: Custom cell renderer on T(row, col)

    Sorry if this was posted before, but the whole Search function doesn't seem to work these days (hasn't been working for a week now). Anyways:
    I know how to create custom cell renderers. My problem lies with which cells I want to apply that cell renderer to. It seems I am limited in setting a cell renderer to a whole column, which I don't want.
    For instance, I'd like to apply cell renderer R1 to (0,0) but not to (1,0) and not to (3,0). Instead I want cell renderer R2 on (2,0) and (3,0).
    Example of my table:
    |--icon--|--filename--|--extension--|
    |   R1   |  file1.txt |     txt     |
    |   R2   |  img1.jpg  |     jpg     |
    |   R1   |  file2.txt |     txt     |
    |   R2   |  img2.jpg  |     jpg     |
    |-----------------------------------|Is there any possibility this can be achieved? I am probably overlooking some method or class, but I don't know which. Some pointers or clues in the right directions are appreciated.
    Thanks

    Camickr, again you've been a great help. Works great, but a NullPointerException is being thrown and I can't find out what points to a null object.
    Code is this:
        public TableCellRenderer getCellRenderer(int row, int column) {
            if (getValueAt(row, 3).equals("jpg") && column == 0) {
                return new IconCellRenderer(Klue.iconAdd);
            } else {
                return super.getCellRenderer(row, column);
        }Solution is catching the NullPointerException in this method, but I'd rather have an if statement checking for it. But what to check? Any ideas?

  • Selection Problem with JTable

    Hello,
    i have a selection problem with JTable. I want to allow only single cell selection and additionally limit the selection to the first column.
    I preffered the style from MS Outlook Express where you can select the email accounts to edit.
    It is a table like this:
    Account name  |   Type  |   ...
    --------------|---------|---------------------
    Hotmail       |   POP3  |
    GMX           |   IMAP  |The selection should be only avaibable at 'Hotmail' or 'GMX' - not at 'POP3', 'IMAP' or as complete row selection.
    Please help me!
    Thanks.
    Warlock

    Maybe this will helpimport java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One", "Two"};
        String[][] data = {{"R1-C1", "R1-C2"}, {"R2-C1", "R2-C2"}};
        JTable jt = new JTable(data, head);
        jt.getColumnModel().setSelectionModel(new MyTableSelectionModel());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setCellSelectionEnabled(true);
        jt.setRowSelectionAllowed(false);
        jt.setColumnSelectionAllowed(false);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class MyTableSelectionModel extends DefaultListSelectionModel {
      public void setSelectionInterval(int index0, int index1) {
        super.setSelectionInterval(0, 0);
    }

  • Another problem with JTable

    Hi,
    I have encountered a problem with JTable, i am trying to display some 15 columns and their values , one of the columns value is null, then the JTable is not displaying its value from this column(which is with null value) onwards.
    Can anybody assiss me in this matter.
    Regards
    khiz_eng

    I don't know If I can fix your problem, but
    I know just that it works on my PC.... It's very very
    slow... I don't know how to insert PageSetUp option... I have to study the problem.....
    However I don't think it's a hard problem....
    I want ask to you if you have found some problems when you are in Editing mode in a cell.....
    in the jdk1.2 version I could save while was in editing mode using the editingStopped method.
    It permit to update all data .... also the data in the cell I was editing.
    in the jdk 1.3 if I use this method It doesn't work properly... It maybe destroy the content object in the Cell..... because I'm able to print all the table except the editing cell (it throw an exception...)
    What's changed????
    I don't know...
    Can u help me?

  • JTable - help with custom cell renderers and editors

    I've got myself into a bit of a mess with cell renderers and editors.
    I've got a custom component that wants displaying in a column and then hand over all functionality to this component when you start editing it.
    Now how I went out about this was to create a custom cell renderer that extends this component and implements TableCellRenderer.
    I then created a table cell editor that extends AbstractCellEditor and implements TableCellEditor and this cell editor creates a new component when it's initialized. I then use setCellEditor(new MyCellEditor()) on the column and setCellRenderer(new MyCellRenderer()).
    This works slightly but I'm wondering how this is all implemented.
    When I set the cell editor on it's own it seems to be sharing a reference to the single component that's being used which means that if you edit one cell all the cells get changed to the new value.
    Thanks for the help,
    Alex

    only a few forums are actually browsedAnd theSwing forum is one of the most active. Did you search it for editiing examples? I've seen many editing examples posted in a SSCCE format.
    SSCEE is also impossible as the functionality spans over about 10 classes We did not ask for your application, we asked for a SSCCE. The whole point of a SSCCE is to simplify the 10 classes into a single class and maybe an inner class for the editor to make sure you haven't made a silly mistake that is hidden because of the complexity of your real application.

  • Problem with select all cells in JTable

    Hi guys! I get some problem about selecting all cells in JTable. I tried to used two methods:
    1> table.selectAll()2> changeSelection(firstcell, lastcell,false,true)
    firstcell:[0,0], lastcell[rowcount-1,colcount-1]
    Result: only the first row selected when i use both methods.
    Note: i set up the selection model as following:
    this.dataSheet.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    this.dataSheet.setCellSelectionEnabled(true);
                    this.dataSheet.setRowSelectionAllowed(true);
                    this.dataSheet.setColumnSelectionAllowed(true);Thanks !

    What selection properity should be changed in order to enable selectAll() method work properly? Is there Any constraints? Here is the TableModel I am using. And i set up selection mode use the following code:
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setCellSelectionEnabled(true);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);
    import java.util.Vector;
    import javax.swing.table.*;
    import javax.swing.JTable;
    public class DataSheetModel extends AbstractTableModel{
              private Vector data = new Vector();//Store data
              private Vector columnNames = new Vector();//Store head
              public DataSheetModel(){}
              public DataSheetModel(Vector headVector, Vector dataVector){
                   if(headVector != null) this.columnNames = headVector;
                   if(dataVector != null) this.data = dataVector;
              public int getColumnCount(){
                   return columnNames.size()+1;
              public int getRowCount(){
                   return data.size()+1;
              public String getColumnName(int col){
                   if(col==0) return "";
                   else return (String)columnNames.get(col-1);
              public Object getValueAt(int row, int col){
                   if(col==0) {
                        if(row != data.size()) return String.valueOf(row);
                        else return "*";
                   else{
                        if(row != data.size()){
                             Vector rowVector = (Vector)data.elementAt(row);
                             return rowVector.elementAt(col-1);
                        }else return null;
              public void setValueAt(Object value, int row, int col){
                   if(row != this.data.size()){
                        Vector rowVector = (Vector)data.elementAt(row);
                        rowVector.set(col-1,value);
                        this.data.set(row,rowVector);
                        this.fireTableDataChanged();
                   }else{
                        Vector rowVector = new Vector();
                        for(int i=0; i<this.getColumnCount()-1; i++) rowVector.add(null);
                        rowVector.set(col-1,value);
                        this.data.add(rowVector);
                        this.fireTableDataChanged();
              public Class getColumnClass(int c){
                   return getValueAt(0,c).getClass();
              public boolean isCellEditable(int row, int col){
                   if(col == 0) return false;
                   else return true;
              public void setDataVector(Vector head, Vector data){
                   if(head != null) this.columnNames = head;
                   if(data != null) this.data = data;
    }

  • Help with JTreeTable custom cell renderer!

    Hi.
    I've followed diligently the complete TreeTable2 example found on the Sun site. http://java.sun.com/products/jfc/tsc/articles/treetable2/
    What I'm trying to do is to add alternate-row shading on the Column(0) of the JTreeTable where the Column class is "TreeTableModel".
    so, from the example, I've added the following setCellRenderer declaration to TreeTableExample2.java:
         protected JTreeTable createTreeTable() {
              JTreeTable       treeTable = new JTreeTable(model);
              treeTable.getColumnModel().getColumn(1).setCellRenderer
              (new IndicatorRenderer());
              treeTable.getColumnModel().getColumn(0).setCellRenderer
              (new MyTableCellRenderer());Then, I subclass DefaultTableCellRenderer as shown below, in a new class called "MyTableCellRenderer"
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    public class MyTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer
         private static final long serialVersionUID = 1L;
         public MyTableCellRenderer() {
         public Component getTableCellRendererComponent(JTable jtable, Object obj, boolean isSelected, boolean hasFocus, int i, int j)
              if (i % 2 == 0 && !isSelected) {
                   this.setBackground(new Color(214,226,255));
                   this.setForeground(Color.BLACK);
              } else if (isSelected)
                   this.setBackground(new Color(204, 204, 255));
              else {
                   this.setBackground(Color.white);
              //if (obj != null)
              this.setValue(obj.toString());
              System.out.println("obj: " + obj.toString());
              System.out.println("obj type: " + obj.getClass().getName());
              return ((Component) (this));
    }I've been pulling out whatever few hairs I have left in my sparse scalp to get this working, but it's looking grim thus far.
    Here are links to screenshots of my progress, or lack thereof:
    Original Working TreeTable II
    http://www.pharmalytix.com/original_treetable.jpg
    My Not-working Tree Table II w/ Custom Cell Renderer
    http://www.pharmalytix.com/customtablecellrenderer_treetable.jpg
    thanks again - !!

    phew! finally got this sucker working. I had to retrieve the default rendererer of my TreeTable's TreeTableModel class column, which is the JTree and then, in its component-form, start mucking about with its stylings. The real black-hole of progress was caused by my brain imploding from not being able to understand that a "Component" was what represented the "thing" whose behaviour I wanted to alter, be it a Jtree node or Jtable cell.
              treeTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer() {
                   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
                        Component comp = treeTable.getDefaultRenderer(TreeTableModel.class).getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                        if (row % 2 == 0 && !isSelected) {
                             comp.setBackground(new Color(214,226,255));
                             comp.setForeground(Color.BLACK);
                        } else
                             if (isSelected)
                                  comp.setBackground(new Color(204, 204, 255));
                             else {
                                  comp.setBackground(Color.white);
                        return comp;
              });In all of its ravishing glory:
    http://www.pharmalytix.com/alternateshading_treetable.jpg
    Edited by: DataHog on Nov 6, 2007 10:21 AM

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

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

  • JTable loses cell renderers

    Well I just had an annoying bug that took me a long time to diagnose.
    Under certain circumstances, my JTable would suddenly redraw using all default cell renderers - my overriding renderers just stopped being used.
    Until today I was not able to reproduce it consistently, but I finally managed to do so, and I found the reason for it.
    It turned out that due to a bug in my code, I was occasionally callingfireTableRowsDeleted(first, last);with first set to -1. This apparently causes any column renderers you've set to be discarded!
    Hopefully this post will be useful if anyone else sees the same loss of renderers.

    It turned out that due to a bug in my code, I was occasionally calling
    fireTableRowsDeleted(first, last);Doesn't seem right. Here is the code from the JTable. A negative value seems to be handled.
    private void tableRowsDeleted(TableModelEvent e)
        int start = e.getFirstRow();
        int end = e.getLastRow();
        if (start < 0)
             start = 0;
        if (end < 0)
            end = getRowCount()-1;
    ...This problem is usually caused by invoking the fireTableStructureChanged() method (which is automatically invoked when you use setModel() or setDataVector()). This method does indeed cause the TableColumnModel to be recreated, which means the TableColumns are also recreated so you lose the old renderers and editors.
    You can prevent this by using the following:
    table.setAutoCreateColumnsFromModel( false );

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

Maybe you are looking for