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

Similar Messages

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

  • JTable loses renderers (Urgent!!!)

    When I refresh my data, the job is done in a thread. When job is finished I call fireTableDataChanged of TableModel with invokeLater system.
    But after that, in some cases, the JTable loses its renderers which are replacing by defaults.
    I use JDK 1.3 on Windows NT or Linux

    Had this problem as well, I solved it by removing my TableColumnModel and replacing it with a defualt one. Then refreshing the data and finally adding my model back. Something like
    TableColumnModel tcm = myJTable.getColumnModel();
    myJTable.setColumnModel(new DefaultTableColumnModel());
    // Refresh
    myJTable.setColumnModel(tcm);
    Might not be optimal but it worked in my app.

  • JTables how to apply multiple cell renderers to a cell

    I have a complicated table with many different cell renderers depending on column type. (i.e check boxes, editable text fields, formatted fields, fields with icons etc..) Now I need to add the capability to color rows depending on a certain status value of a column. How can I add this capability since I already have renderers for the cells> Most examples I have seen for manipulating row colors simply extends DefaultCellRenderer for the entire table, but I already have renderers for these cells.

    Create an interface and make each renderer implement a method that colours in the background for you. Just an idea, haven't tried it myself

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

  • Request For Enhancement: Cell Renderers: Is the Mouse In the Cell?

    I would like to propose an enhancement to Cell Renderers: add some way for Cell Renderers to know if the mouse is currently over the cell being renderered. Currently, Cell Renderers are told only if a cell is SELECTED or has FOCUS, which are not the same thing.
    This would be of great help especially for JTable and JTableHeader, where one could provide visual feedback as the mouse moves across cells, which could be a great help for the visually impaired.

    Hi, Marsian -
    You are absolutely right about adding methods to interfaces. My mistake.
    And you are also correct that what I propose would require that cells be repainted as the mouse enters or exits that cell's bounds. If this were to prove too expensive for some applications, the JComponents that use CellRenderers could have a property to enable or disable the behavior, for example setTrackMouseMovements(boolean). But when compared to what happens when you scroll a JTable, I cannot imagine this would be anywhere nearly as expensive, and the rendering that scrolling requires--all the cells that come into view within the viewport after scrolling--seems to work just fine.
    Heck, even when you select a cell, a whole lot of cells are re-rendered. Also, when a tooltip is currently visible, if you move the mouse, the CellRenderer is consulted for each and every mouse movement, even within the same cell!!!. This seems to work fine too. Would re-rendering a cell as the mouse enters or exits its bounds by anywhere nearly as expensive?
    But you write something that still confuses me. Are you saying that you create a new Component each and every time the getXXXRendererComponent() method of your CellRenderer is called? I don't understand why one would want to do this. Can you please help me out here?
    I would think that only one instance of each Component sub-class that the CellRenderer might return would be more than good enough. And I would think that these instances would be created in the CellRenderer's constructor. Certainly, the default CellRenderer classes do not create a new Component each time a cell needs to be renderered. In fact, most of them actually extend an extension of JComponent themselves, i.e. JLabel, and return "this". No CellRenderer I have ever written has ever created a Component each time a cell is rendered. That would be very expensive.
    But still, your point about altering interfaces is well taken. Too bad.
    There must be some solution to this problem. JTable could provide the cell coordinates of the cell in which the mouse currently resides, for instance, or it could have a method that indicates if the mouse is currently over a cell with given coordinates.
    Thanks,
    ---Mark

  • Need urgent help on JTable and cell

    Hi,
    I've got problem in validating the cell in Table.
    If user enters data in a cell i would like to validate the data in cell and if it is wrong i would like to give a dialog and keep the cursor in the same cell. So that i can restrict the user to enter valid data.
    How do i capture the event when he is leaving the cell using tab/mouse press?
    Suppose if the cursor is in once cell from a row (the rew contains different cell renderers,) then he wish to delete the row then i would like to save the data in the model and delete it.
    I'm getting class cast exception as i have got differnt components inside row.
    Thanks

    Hi,
    Try out the following code.
    import javax.swing.*;
    import javax.swing.table.*;
    class EditingTest
         EditingTest()
              JFrame frame = new JFrame("Editing Test");
              frame.setBounds(10,10,750,550);
              JTable table = new JTable(5,5);
              TableCellEditor tableCellEditor = new CustomEditor(new JTextField());
              for(int i = 4; i > -1; --i)
                   table.getColumnModel().getColumn(i).setCellEditor(tableCellEditor);
              JScrollPane scrollpane = new JScrollPane(table);
              frame.getContentPane().add(scrollpane);
              frame.setVisible(true);
         public static void main(String [] args)
              EditingTest appln = new EditingTest();
    class CustomEditor extends DefaultCellEditor
         CustomEditor(JTextField editorComponent)
              super(editorComponent);
         public boolean stopCellEditing()
              try
                   String editingValue = (String)getCellEditorValue();
                   if(editingValue.length() != 5)
                        JOptionPane.showMessageDialog(null,"Please enter string with 5 letters.", "Alert!",JOptionPane.ERROR_MESSAGE);
                        return false;
              catch(ClassCastException exception)
                   return false;
              return super.stopCellEditing();
    }

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

  • Rubber stamp table cell renderers performance

    One never stops to learn...
    http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableCellRenderer.html
    +“...So this class overrides the validate, invalidate, revalidate, repaint, and firePropertyChange methods to be no-ops and override the isOpaque method solely to improve performance. If you write your own renderer, please keep this performance consideration in mind.”+
    Hm. This was quite a revelation for me. However, I’m having troubles implementing it. I have rather complex cell renderers… To be exact: I have complex cell editors, for example one containing two textfields and two buttons (key & description textfields plus zoom & search buttons) inside a JPanel. The JPanel is the cell editor component. Because I want the buttons on exactly the same location in the renderer as in the editor, I have an editor-to-renderer wrapper.
    I cannot disable the mentioned methods on the JPanel that is the renderer, then its contents isn’t painted anymore. Invalidate and validate must stay.
    Now, I can easily build a simple text based renderer using DefaultTableCellRenderer aka JLabel. However, what if a table must show more than trivial stuff? Are there any good guides on how to build complex cell renderers?
    Again: I often use the editor-as-renderer wrapper in order to not have to code stuff twice. At all works just fine, but appearantly is very slow (my tables are slow indeed)... Any way to do this correctly?

    Ok, here you are with two SSCCE's! :-)
    The first test only shows a regular complex renderer (2x textfield, 2x button). According to the specs the component must have certain methods disabled, so they are overridden in the jpanel that holds all these components. Run, and then try again with the two methods uncommented.
    The second test is how I normally do it; I do not want to write separate editors and renderers, so I only write the editor and use an editor-to-renderer wrapper. In order to fulfill the requirement, I wrap the editor component in a second jpanel that overrides the required methods. Again, run and then try again with the two methods uncommented.
    package test;
    import java.awt.Component;
    import java.awt.GridLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    * Test1: use a complex cell renderer and follow the specs in
    * http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableCellRenderer.html
    public class CellRendererTest
          * @param args
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable()
                   @Override
                   public void run()
                        JTable lJTable = new JTable(new DefaultTableModel(new String[][]{{"a1","b1"},{"a2","b2"}}, new String[]{"A","B"}));
                        lJTable.setDefaultRenderer(Object.class, new ComplexCellRenderer());
                        JFrame lJFrame = new JFrame();
                        lJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        lJFrame.add(lJTable);
                        lJFrame.setSize(500,100);
                        lJFrame.setVisible(true);
         // =============================================================================
         static class ComplexCellRenderer implements TableCellRenderer
              JTextField iKey = new JTextField(5);
              JButton iSearch = new JButton("?");
              JButton iGoto = new JButton(">");
              JTextField iDescription = new JTextField(20);
              JPanel iJPanel = new JPanel()               
    //               @Override public void validate() {}
    //               @Override public void invalidate() {}
                   @Override public void revalidate() {}
                   @Override public void repaint() {}
                   @Override public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
                   @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
                   @Override public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
              public ComplexCellRenderer()
                   iKey.setBorder(null);
                   iDescription.setBorder(null);
                   iDescription.setEnabled(false);
                   iJPanel.setLayout(new GridLayout());
                   iJPanel.add(iKey);
                   iJPanel.add(iSearch);
                   iJPanel.add(iGoto);
                   iJPanel.add(iDescription);
              @Override
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                   iKey.setText( value == null ? "" : value.toString() );
                   iDescription.setText( value == null ? "" : value.toString() + "..." );
                   return iJPanel;
    }Test 2:
    package test;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.GridLayout;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    * Test2: usually when have complex cell renderers, it actually means you have complex cell editors.
    * You want the renderer to look 100% like the editor, so it is practical to implement a wrapper.
    * Naturally the wrapped editor must adhere to the specs in: 
    * http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableCellRenderer.html
    * So the idea is the wrap it in a special panel, this is what the "useAsRenderer" method is for.
    public class CellRendererTest2
          * @param args
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable()
                   @Override
                   public void run()
                        JTable lJTable = new JTable(new DefaultTableModel(new String[][]{{"a1","b1"},{"a2","b2"}}, new String[]{"A","B"}));
                        lJTable.setDefaultEditor(Object.class, new ComplexCellEditor());
                        lJTable.setDefaultRenderer(Object.class, new UseTableCellEditorAsTableCellRenderer(new ComplexCellEditor().useAsRenderer()));
                        JFrame lJFrame = new JFrame();
                        lJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        lJFrame.add(lJTable);
                        lJFrame.setSize(500,100);
                        lJFrame.setVisible(true);
         // =============================================================================
         // The editor
         static class ComplexCellEditor extends AbstractCellEditor  implements TableCellEditor
              JTextField iKey = new JTextField(5);
              JButton iSearch = new JButton("?");
              JButton iGoto = new JButton(">");
              JTextField iDescription = new JTextField(20);
              JPanel iJPanel = new JPanel();
              public ComplexCellEditor()
                   super();
                   iKey.setBorder(null);
                   iDescription.setBorder(null);
                   iDescription.setEnabled(false);
                   iJPanel.setLayout(new GridLayout());
                   iJPanel.add(iKey);
                   iJPanel.add(iSearch);
                   iJPanel.add(iGoto);
                   iJPanel.add(iDescription);
              @Override
              public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
                   iKey.setText( value == null ? "" : value.toString() );
                   iDescription.setText( value == null ? "" : value.toString() + "..." );
                   return iJPanel;
              @Override
              public Object getCellEditorValue()
                   return iKey.getText();
              public ComplexCellEditor useAsRenderer()
                   JPanel lJPanel = new JPanel()
    //                    @Override public void validate() {}
    //                    @Override public void invalidate() {}
                        @Override public void revalidate() {}
                        @Override public void repaint() {}
                        @Override public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
                        @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
                        @Override public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
                   lJPanel.setLayout(new BorderLayout());
                   lJPanel.add(iJPanel);
                   iJPanel = lJPanel;
                   return this;
         // ==========================================================================================
         // Simplified version of the wrapper (normally this wrapper takes care of the special JPanel)
         static class UseTableCellEditorAsTableCellRenderer implements TableCellRenderer
              public UseTableCellEditorAsTableCellRenderer(TableCellEditor tableCellEditor)
                   iTableCellEditor = tableCellEditor;
              private TableCellEditor iTableCellEditor = null;
              @Override
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                  // we use the editor as the renderer
                  Component lEditor = iTableCellEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
                  return lEditor;
    }

  • Need help serializing an AbstractTableModel for a JTable with cell editing.

    Fun times are ahead. Here we go!
    I have a JTable that contains data I'd like to serialize out to a file to be restored and viewed later.
    So I tried saving the AbstractTableModel subclass out to a file. Whenever I do this, I get the following error message:
    java.io.NotSerializableException: javax.swing.JTable$CellEditorRemover
    Now I know for fact that serializing an AbstractTableModel that was installed in a JTable without cell editing works just fine (my old code did exactly that). As a result, I think that the code that handles events in the AbstractTableModel contains references back out to the JTable, which causes the JTable to be saved no matter what (even though I'm just interested in saving the TableModel only). It causes a bigger file than normal, but file size is not an issue. The only issue I have is that CellEditorRemover (an undocumented inner class of JTable), which is automatically installed for JTables with editable cells, is not serializable.
    This leads to the following questions:
    1. Is there a way to avoid serialization/deserialization of the CellEditorRemover inner class of JTable?
    2. Is there a way to save an AbstractTableModel without saving all of the event listeners associated with it?
    I think an answer to either of these questions would go a long way towards solving my problem. Otherwise, I'll resign myself to weeping silently in the corner of my office.
    Thanks!

    I would suggest that if you can you only save the
    data... but i would do this by using the
    externalizable interface.
    What you will need to do is have the
    writeExternal(ObjectOutputStream out) and
    readExternal(ObjectOutputStream out) methods in your
    class. These will be responsiable for saving the
    data.
    Here's an example of what you can do in these
    methods... this is just a little tidbit from a program
    i've written.public void writeExternal(ObjectOutput out) throws
    IOException {
              out.writeInt(size);
              out.writeObject(drawName);
              out.writeInt(playersLength);
    for(int i = 0; i < playersLength; i++)
    ) out.writeObject(players);
              out.writeInt(seedsLength);
    for(int i = 0; i < seedsLength; i++)
    ) out.writeObject(seeds[i]);
              out.writeInt(drawLength);
    for(int i = 0; i < drawLength; i++)
    ) out.writeObject(draw[i]);
    public void readExternal(ObjectInput in) throws
    IOException, ClassNotFoundException {
              size = in.readInt();
              drawName = (String)in.readObject();
              playersLength = in.readInt();
    for(int i = 0; i < playersLength; i++) players[i] =
    = (String)in.readObject();
              seedsLength = in.readInt();
    for(int i = 0; i < seedsLength; i++) seeds[i] =
    = (String)in.readObject();
              drawLength = in.readInt();
    for(int i = 0; i < drawLength; i++) draw[i] =
    = (String)in.readObject();
    You can now use your class as you would a Serializable
    class, but it will only save the data
    Hope this helped
    webaf409java
    I forgot to add some critical information in my original post. My apologies. :(
    I've thought about using Externalizable, but am hesitant to use it because the application would no longer be able to read in files using the old save format (ie, AbstractTableModels for JTables without CellEditorRemovers ).  I want to preserve the ability to read the old saved AbstractTableModel formats if possible. 
    Do you know of a way to revert to the default deserialization mechanism from readExternal?  This way, during deserialization, I could do a quick test on the object being read and have the ability to default to the regular deserialization mechanism if the object is of the old type or continue with the new Externalizable stuff if the object is one of the new type.  Maintaining file compatibility is key.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • JTable's Cell navigation with TAB

    Dear ALL
    I have face one problem in JTable's cell navigation with TAB. The problem as describe bellow.
    I have two columns NAME and ADDRESS. Set focus on ADDRESS column's first cell. now if i am press tab key then focus controll comes on second cell which is the ADDRESS column. At the end of row controll comes on first row second column that means focus on ADDRESS column's first cell.
    Please give me some hints.
    Thanks in advance.
    Amit

    Your description doesn't make any sense (to me at least) so I don't know what your problem is or what you are asking to be changed.
    The normal tab order is Left to Right, Top to Bottom. So if the focus is at the top/left normal tabbing would be:
    Row 0, Column 0 (name 0)
    Row 0 Column 1 (address 0)
    Row 1, Column0 (name 1)
    Row 1, Column 1 (address 1)
    Row 2, Column 0 (name 2)
    Row 2, Column 1 (address 2)
    Your question seems to imply that your tab from address to addreass, which doesn't make sense.
    "Set focus on ADDRESS column's first cell. now if i am press tab key then focus controll comes on second cell which is the ADDRESS "

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

  • JTable - active cell not highlited when editable

    Hello,
    I'm using JDK 1.4.2_05, and I'm seeing some behavior that seems a bit strange.
    In my JTables, some cells are editable, and others are not. When the user moves the active cell around (with the arrow keys, or TAB and RETURN) the non-editable cells show up with a nice blue color. If a cell is editable, it doesn't change at all, so the user has no idea where the "cursor" (meaning the active cell) is.
    These cells don't have any special renderer or anything. My JTable has these set:
    setRowSelectionAllowed(false);
    setColumnSelectionAllowed(false);
    setCellSelectionEnabled(true);Thanks for any advice!
    --- Eric

    Okay, yeah, I overrode the default renderer, and had it check whether the cell was selected or not, setting the background color appropriately. Duh. --- Eric

  • Jtable on cell changed event

    How can i treat an Jtable on cell changed event, not on value changed

    Do you mean cell selection changed? One way is to add a ListSelectionListener to both the table's and the table's ColumnModel's ListSelectionModels. Something likeListSelectionListener lsl = new ListSelectionListener() {
       public void valueChanged(ListSelectionEvent e) {
          System.out.println(e.getSource());
          ListSelectionModel lsm = (ListSelectionModel) e.getSource();
          if (!lsm.getValueIsAdjusting()) {
             System.out.println("Selection changed");
    table.getSelectionModel().addListSelectionListener(lsl);
    table.getColumnModel().getSelectionModel().addListSelectionListener(lsl);Note that simultaneous change of both row and column will generate two valueChanged events.
    If that's not what you wanted to know, ask a better question.
    [http://catb.org/~esr/faqs/smart-questions.html]
    db

  • HELP!!!Embedding a JTable on a ScrollPane into a JTable's cell

    I have a single column DND JTable on a DND JScrollPane that I would like to put into another's JTable's cell. I've tried creating a CellRenderer that extends the DNDJScrollPane and returns this but this doesn't work. I do have code I could post if anyone is interested in helping out.

    First copy this and compile and run and c.. then look at the code
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    public class JTableExample extends JFrame
    JTableRenderer renderer;
    MyTableModel m1, m2;
    public JTableExample()
    super();
    m1 = new MyTableModel();
    m2 = new MyTableModel();
    DefaultTableModel dtm = new DefaultTableModel()
    // make first cell uneditable
    public boolean isCellEditable(int row, int column)
    return !(column == 0);
    dtm.setDataVector(new Object[][]{{ "JTable1",  m1},
    { "JTable2",  m2}},
    new Object[]{ "Column1","Column2"});
    JTable table = new JTable(dtm);
    renderer = new JTableRenderer();
    table.getColumn("Column2").setCellRenderer(renderer);
    table.getColumn("Column2").setCellEditor(new JTableEditor());
    table.setRowHeight(80);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
    setSize( 400, 250 );
    setVisible(true);
    public static void main(String[] args) {
    JTableExample frame = new JTableExample();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    * JTable Editor
    class JTableEditor extends DefaultCellEditor
    public JTableEditor()
    super(new JCheckBox());
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column)
    return renderer;
    public Object getCellEditorValue()
    return (MyTableModel)((JTableRenderer)renderer).jtable.getModel();
    * JTable Renederer
    class JTableRenderer extends JScrollPane implements TableCellRenderer
    JTable jtable;
    public JTableRenderer()
    jtable = new JTable();
    getViewport().add(jtable);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column)
    if (isSelected)
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    jtable.setForeground(table.getSelectionForeground());
    jtable.setBackground(table.getSelectionBackground());
    else
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    jtable.setForeground(table.getForeground());
    jtable.setBackground(table.getBackground());
    jtable.setModel((AbstractTableModel)value);
    return this;
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", "Andrews",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    public final Object[] longValues = {"Angela", "Andrews",
    "Teaching high school",
    new Integer(20), Boolean.TRUE};
    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 < 2) {
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    if (data[0][col] instanceof Integer
    && !(value instanceof Integer)) {
    try {
    data[row][col] = new Integer(value.toString());
    fireTableCellUpdated(row, col);
    } catch (NumberFormatException e) {
    } else {
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    private void printDebugData() {
    cheers
    good luck

Maybe you are looking for

  • Backing up iPad to a different computer

    Question:  I have a full iPad, and want to back it up to a new (to it) laptop. Details:  My macbook pro died (water spill).  My time machine is out of date--it went out of sync four months ago, and I hadn't gotten around to setting up a new one.  I'm

  • How to install wired printer via rj45 on Extender RE2000 connected to router EA6700

    Hi, I´ve installed a new network at home but I´ve problem when trying to connect my printer to my RE2000. Someone who know how to do? // Kent

  • Balance Decrease = Score Decrease?

    So, I got an alert today which says that my credit card balance decreased by 55% which lead to a 6 pt drop in my score. Does this sound right? If I am paying off my credit card balance, why is my score dropping instead of increasing? Please hep me un

  • TreeTable can't change title

    I change TreeTableColumn.text but I got a Exception Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: javafx.scene.control.TreeTableColumn cannot be cast to javafx.scene.control.TableColumn     at com.sun.javafx.scene.cont

  • Regarding ale

    hi, pls explain some one why we need a ale in organization? pls also send some fs telated to thing for better understanding. mail  me: [email protected] thanks for advance with regards lokeshan