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.

Similar Messages

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

  • Adding Image in JTable - help needed(Urgent).

    Hai Friends,
    i want to add two icon in the cells of JTable... i dont know where am going wrong... the icon is not getting displayed in the cell but instead if i double click the cell the name of the icon is displayed in editable mode... any suggestion...
    this is my code... i got this from the forum only... but tis not working....
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableIcon extends JFrame
         public TableIcon()
              String[] columnNames = {"Picture", "Description"};
              Object[][] data =
                   {new ImageIcon("juggler.ico"), "Copy"},
                   {new ImageIcon("favicon.gif"), "Add"},
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
          System.out.println("getValueAt(0, column)"+getValueAt(0, 0));
                        return getValueAt(0, 0).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableIcon frame = new TableIcon();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }Urgent... pls help...
    Regards,
    Ciya.

    Hai Chris,
    Thanks for ur reply,
    Now Its throwing null pointer exception in the URL....
    Can u pls look into d code and tell me pls...
    import java.awt.Component;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.net.URL;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellRenderer;
    public class MyIcon extends JPanel
      private JScrollPane jScrollPane1 = new JScrollPane();
      private JTable jTable1;
      private GridBagLayout gridBagLayout1 = new GridBagLayout();
      public MyIcon()
        try
          jbInit();
        catch(Exception e)
          e.printStackTrace();
      private void jbInit() throws Exception
        this.setLayout(gridBagLayout1);
        jTable1 = new JTable(new AbstractTableModel()
         URL lURL = getClass().getResource("file:///D:/Eg/TWEETY.GIF");
          URL lURL2 = getClass().getResource("file:///D:/Eg/TWEETY.GIF");
        Object[][] data =
            {new ImageIcon(lURL), "Copy"},
            {new ImageIcon(lURL), "Add"},
          public int getRowCount()
            return 2;
         public int getColumnCount()
           return 2;
         public Object getValueAt(int row, int column)
           return data[row][column];
        jTable1.getColumnModel().getColumn(0).setCellRenderer(new Renderer());
        jScrollPane1.getViewport().add(jTable1, null);
        this.add(jScrollPane1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(60, 20, 125, 25), -97, -287));
      public static void main(String a[])
        MyIcon c = new MyIcon();
        JFrame f = new JFrame();
        f.getContentPane().add(c);
        f.setSize(400,400);
        f.setVisible(true);
      class Renderer extends JLabel implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected,
    boolean hasFocus,
    int row, int column) {
    setIcon((ImageIcon) value);
    return this;
    }Ciya...

  • JTable: renderer problem-urgent

    Thanx "pasteven". That url is too good.
    I wrote my own renderer for each cell in JTable that uses JCombobox for rendering purpose. But when i select an item in that combo box, some times renderer is not setting the selected item in that combobox. Sometimes when i change the selection of item in the previous cell,it is getting reflected in all other cells of that particular column.
    Here is my code. Please help me.
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.table.TableCellEditor.*;
    import javax.swing.table.*;
    import javax.swing.DefaultCellEditor;
    public class Render extends javax.swing.JFrame {
    JTextField textField0=new JTextField();
    JComboBox cmb_Editor1=new JComboBox();
    JComboBox cmb_Editor2=new JComboBox();
    JComboBox cmb_Editor3=new JComboBox();
    EachRowRenderer rend;
    EachRowEditor eee;
    /** Creates new form Render */
    public Render() {
    initComponents ();
    rend=new EachRowRenderer();
    eee=new EachRowEditor(table);
    table.setDefaultRenderer(java.lang.Object.class,rend);
    table.setDefaultEditor(java.lang.Object.class,eee);
    cmb_Editor3.addItem("Y");
    cmb_Editor3.addItem("N");
    eee.setEditorAt(0,1,new DefaultCellEditor(cmb_Editor3));
    eee.setEditorAt(1,1,new DefaultCellEditor(cmb_Editor3));
    eee.setEditorAt(2,1,new DefaultCellEditor(cmb_Editor3));
    eee.setEditorAt(0,2,new DefaultCellEditor(new JCheckBox()));
    rend.add(0,2,new CheckBoxCellRenderer());
    rend.add(0,1,new ComboBoxCellRenderer(cmb_Editor3));
    rend.add(1,1,new ComboBoxCellRenderer(cmb_Editor3));
    rend.add(2,1,new ComboBoxCellRenderer(cmb_Editor3));
    JCheckBox chk=new JCheckBox();
    pack ();
    public class EachRowEditor implements TableCellEditor {
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    JTable table;
    public EachRowEditor(JTable table) {
    this.table = table;
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void setEditorAt(int row,int column, TableCellEditor editor) {
    editors.put(""+row+column,editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    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) {
    selectEditor((MouseEvent)anEvent);
    // editor.isCellEditable(anEvent);
         return true;
    public void addSeperateCellEditorListener(int row,int column,CellEditorListener l) {
    editor=(TableCellEditor)editors.get(""+row+column);
    editor.addCellEditorListener(l);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    selectEditor((MouseEvent)anEvent);
    return editor.shouldSelectCell(anEvent);
    protected void selectEditor(MouseEvent e) {
    int row;
    int column;
    if (e == null) {
    row = table.getSelectionModel().getAnchorSelectionIndex();
    column=table.getSelectionModel().getLeadSelectionIndex();
    } else {
    row = table.rowAtPoint(e.getPoint());
    column=table.columnAtPoint(e.getPoint());
    editor = (TableCellEditor)editors.get(""+row+column);
    if (editor == null) {
    editor = defaultEditor;
    public class CheckBoxCellRenderer extends JCheckBox implements TableCellRenderer
    CheckBoxCellRenderer() {
    setHorizontalAlignment(JLabel.CENTER);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setSelected((value != null && ((Boolean)value).booleanValue()));
    setToolTipText("checkbox");
    return this;
    public class TextFieldCellRenderer extends JTextField implements TableCellRenderer
    JTextField textField;
    TextFieldCellRenderer(JTextField textField) {
    this.textField=textField;
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setText((textField.getText() != null) ? textField.getText() : "");
    return textField;
    public class ComboBoxCellRenderer extends JComboBox implements TableCellRenderer
    JComboBox comboBox=null;
    ComboBoxCellRenderer(JComboBox comboBox) {
    this.comboBox=comboBox;
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setSelectedItem(comboBox.getSelectedItem());
    return this;
    public class EachRowRenderer implements TableCellRenderer {
    protected Hashtable renderers;
    protected TableCellRenderer renderer, defaultRenderer;
    public EachRowRenderer() {
    renderers = new Hashtable();
    defaultRenderer = new DefaultTableCellRenderer();
    public void add(int row,int column ,TableCellRenderer renderer) {
    renderers.put(""+row+column,renderer);
    public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
    renderer = (TableCellRenderer)renderers.get(""+row+column);
    if (renderer == null) {
    renderer = defaultRenderer;
    return renderer.getTableCellRendererComponent(table,
    value, isSelected, hasFocus, row, column);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the FormEditor.
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    table.setModel(new javax.swing.table.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"
    Class[] types = new Class [] {
    java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
    public Class getColumnClass (int columnIndex) {
    return types [columnIndex];
    jScrollPane1.setViewportView(table);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit (0);
    * @param args the command line arguments
    public static void main (String args[]) {
    new Render ().show ();
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
    Please help me.

    I ran into the same problem in Java 1.4. The problem is that the JTable is not feeding the initial value to the cell editor. I found the following workaround. You have to override the JTable method prepareEditor() like this:
    <CODE>
    public Component prepareEditor(TableCellEditor editor, int row, int column) {
    Component ret = super.prepareEditor(editor, row, column);
    // Translate column to the data model coordinates by using the
    // identifier. We'll check only for the JComboBox columns (in
    // this example columns 8 and 9).
    int col = 0;
    String id = (String)getColumnModel().getColumn(column).getIdentifier();
    if ( id.equals( tableModel.getColumnName(8) ) )
    col = 8;
    else if ( id.equals( tableModel.getColumnName(9) ) )
    col = 9;
    if (col == 8 || col == 9) {
    String item = (String)tableModel.getValueAt(row, col);
    ((JComboBox)((DefaultCellEditor)editor).getComponent()).setSelectedItem( item );
    return ret;
    </CODE>
    You have to translate from table coordinates to table model coordinates in case the user reorders column - if you don't allow this for your table then you won't have to do this.

  • JTable Display problem (urgent)

    Hi all,
    Does anyone here know how to make a all columnns in my table visible
    This is my code. It simple bunches up the columns but I need them spaced out.
    Thanks all :)
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class TableProblem extends JFrame {
    Vector rows, columnHeads;
    BorderLayout borderLayout1 = new BorderLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JTable jTable1 = new JTable();
    public TableProblem ()
    testData(); // used to put data in the vectors for the table
    initTable(); // used to instantiate and setup the gui
    setSize(1100,600);
    show();
    public static void main(String[] args) {
    TableProblem tprob = new TableProblem();
    public void testData ()
    int mc = 100;
    int mr = 100;
    int k = 0;
    Vector temp;
    columnHeads = new Vector();
    for (int i=0; i<mc; i++)
    columnHeads.addElement(Integer.toString(i));
    rows = new Vector();
    for (int i=0; i<mr; i++)
    temp = new Vector();
    for (int j=0; j<mc; j++)
    temp.addElement(Integer.toString(k++));
    rows.addElement(temp);
    public void initTable()
    getContentPane().setLayout(borderLayout1);
    jTable1 = new JTable(rows,columnHeads);
    jScrollPane1 = JTable.createScrollPaneForTable(jTable1);
    getContentPane().add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add(jTable1,null);
    jScrollPane1.getViewport().add(jTable1, null);
    jTable1.setMinimumSize(new Dimension(8000,2000));
    /****************************************************/

    If I understood you correctly, I think this is what you need:
    // Prohibit table from resizing itself
    jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    Regards,
    Boris

  • How to make JPanel as JTable Cell Editor (Urgent help needed)

    Hi!
    I want to make JPanel (with a JTextField, 3 JLabels and 1 JTextArea) as cell editor for one column. Can somebody help me on this?
    Does anybody have any sample code? I will greatly appreciate ur help.
    Thanks,
    Snehal

    Okie. In "How to use JTables" page found in the JAVA website (there is a link from the JTable section of the JAVA API documentation), there is a sample code for a sample color chooser. What this does is, adds a button with its action listener set to pop up a color chooser window. In this, rendering is still through a JLabel.
    This example would be of good help to you. Plus, this example gives me a feeling that what u ask is possible.

  • Problem with refreshing jtable. help please urgent.

    hi there
    i can refresh the table now, but the problem is that every time it refreshes, it adds the same data to the freshed table. i just need the table to display what was displayed few seconds ago unless there is change in the datasource. here is my code:
    public void run()
    String selectSQL = "select * from buyerordertable";
    int rowCounter = 1;
    boolean okay = true;
    ResultSet rs;
    Vector rowdata = new Vector();
    Vector columNames = new Vector();
    columNames.add("order Id");
    columNames.add("suplier name");
    columNames.add("item name");
    columNames.add("model");
    columNames.add("quantity");
    columNames.add("price");
    columNames.add("description");
    columNames.add("job Id");
    columNames.add("order confirm Id");
    while (okay)
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:wgclientdatabase", "admin", "");
    PreparedStatement ps = con.prepareStatement(selectSQL);
    rs = null;
    rs = ps.executeQuery();
    while(rs.next())
    Vector temp =new Vector();
    String orderid = rs.getString("OrderID");
    temp.add(orderid);
    String supplier =rs.getString("supplierName");
    temp.add(supplier);
    String item = rs.getString("ItemName");
    temp.add(item);
    String model = rs.getString("Model");
    temp.add(model);
    String quantity = rs.getString("Quantity");
    temp.add(quantity);
    String price = rs.getString("Price");
    temp.add(price);
    String description = rs.getString("Description");
    temp.add(description);
    String jobid = rs.getString("JobID");
    temp.add(jobid);
    String confirmid = rs.getString("OrderConfirmID");
    temp.add(confirmid);
    rowdata.add(temp);
    }catch (SQLException sqle)
    catch(ClassNotFoundException ce)
    try
    /*the table keeps adding old data to the refreshed table. i start with one row of data, after every second, a new row of same data is added to the table. i don't know why.*/
    DefaultTableModel newmodel =(DefaultTableModel)jTable.getModel();
    newmodel.setDataVector(rowdata, columNames);
    jScrollPane.repaint();
    Thread.sleep(1000);
    catch (InterruptedException e)
    okay = false;
    }

    hi there
    thank you for your reply
    doesn't the tablemodel keep one set of data? every time i refresh the table, the table model should only provide same data over and over unless it is reset again? in my program, the result seems like the table model is cumulating data every time it refreshes. and the display is growing with the same data. i already use the
    newmodel.setDataVector(rowdata, columNames);
    to reset the data. ideally the table should only display rowdata. some people say that just using table model will solve the refreshing task. i am not sure if they have my kind of problem.

  • JTable loses selection with custom renderes

    Hello,
    I have a JXTreeTable with five columns, out of which I have custom rendered 3 columns. When I select a node is the tree, the corresponding columns are selected except the custom rendered columns. Any reason why it would be so?.
    I have set the row selection enabled to be true.
    I know I shouldnt be posting JXTreeTable questions here, but am hoping any JTable guru's might be able to help me out
    Thanks
    K

    The general structure of the renderer code would be:
    class CustomRenderer 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);
              if (! isSelected)
                   // add your custom code here to change background
              return this;
    }

  • JTable Listener problem - Urgent Please:)

    How to make listeners detect both change of rows and columns.
    I used ListSelectionListners but that only fires on change of row., How do I detect change of column within the same row?
    Sincerely,

    d

  • Problem faced with Jtable

    I have a row added to JTable.I am trying to edit column 2 in it.Now i keep my cursor in the same column which is being edited (i.e the focus remains in the column being edited) & click on Cancel Button
    By means of this button i clear the Jtable.i.e delete the row which is added to it.
    Now i add 1 more row to this Jtable.
    The same column of the newly added row displays the contents which had been edited previously.
    Eg : Row consists of 3 columns Col. 1 : Name
    Col 2 : Roll No
    Col 3 : Place .
    Assume that i add a row with name pradeep Roll No. 2 & Place - Mumbai.
    I edit col. 2 having roll no. 2 & make it 3.Keeping the focus here only i click on cancel.
    This row has been thus deleted.Now i add a new row..which has name : Manish Roll No : 5 & Place : Mumbai.But Column 2 shows 3 instead of 5.
    I have tried Jtable..repaint();
    jtable.updateUI();
    jtable.lostFocus();
    jtable.getCellEditor().stopCellEditing();
    however still this happens...is there any way to make jtable lose focus externally.....or any other way to handle this.

    It's the same what i have explained, though it's not real stuff..the idea is the same....yet i have clarified things below also...i have an textfield wherein i enter the main code.I click on enter & the details related to this code get added to the grid.Like in the example given be4...Let's assume i enter 1 i.e the code in the textfield & click on enter.The details related to 1 are Name : Pradeep Roll No. : 2 & Place : Mumbai.(Note that Name,Roll No & Place are column names)
    This gets added to the grid.Now i change the Roll No. which is currently 2 to 3.My focus is in this column.For some reason i don't need this record & click on cancel button.
    Now i enter 2 in the Textfield & click on enter. The details expected to be seen in the added row are Name : Manish , Roll No. 5 & Place Mumbai.But what is seen instead of this is Name : Manish , Roll No. 3 & Place : Mumbai.Also the focus is already in column 2.
    When we edit a column the code added changes the column data & then calls
    jTable.getCellEditor().cancelCellEditing().
    The code on clicking cancel calls
    jtable.repaint();
    jtable.updateUI()
    if (jtblBarCodeDetails.isEditing()) {
    jtblBarCodeDetails.getCellEditor().stopCellEditing();
    well.....that is it..

  • JTable with JButton Cell renderer

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

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

  • JTable Cell Focus Problem

    I am using the setValueAt method in the TableModel of a JTable in order to do validation of the value the user has entered into a cell of a table (the validation involves looking at the values of other components on the same JFrame).
    Everything works fine, except for the following case: The person enters a value into the cell of the editor. The person then moves the focus to another component via a mouse-click. The cell in the table still shows the new value entered by the person, but the setValueAt method is never triggered, and <table>.getValueAt(<row>,<col>) shows the value of the cell prior to the change.
    Is there a way to ensure the setValueAt method of the TableModel is triggered before the JTable loses focus? Or is there a better (i.e. correct) way to accomplish this (ensuring a cell change is 'committed' to the table before
    losing focus)?

    Bug? What Bug? Sun considers this a feature....LOL
    Here is my work-around:
       public boolean editCellAt(final int row, final int col, EventObject e) {
          if (e instanceof MouseEvent) {
             if (((MouseEvent)e).getClickCount()<2) {               // single click on a cell other than the one being edited causes editing to stop
                if (isEditing())getCellEditor(getEditingRow(),getEditingColumn()).stopCellEditing();
                return false;
          return super.editCellAt(row,col,e);                         // cell editing on a keyevent or a double mouse click
       }This is will if the mouse is clicked elsewhere on the same table. I have a lot of other tricks for JTable and things....check out my web site at:
    http://www.aokabc.com
    ;o)
    V.V.

  • Lost CellRenderer when updating TableModel

    I am working on some code, where I need to modify the displayed columns in a table.
    The table consists of cells that uses a custom CellRenderer implemented by the class MonitorCellRenderer.
    So far I have some of the functionality working in that I can make the table display less columns. This is achieved by modifying the data stored in the TableModel. In fact what I do is re-create the Column Headers and data.
    This is all achieved by firing a fireTableStructureChanged() event. Then I recompose the data in the Table Model. I call JTable.setModel() with the Table Model reference again, and the table is re-structured. BUT....
    The cell rendering does not work, all that is displayed is the object reference for the data (The data for each cell is stored in an object). This is the same as would have happened if I had not initialised a CellRenderer for the table, so I implemented the following code in my TableModelListener
    for(int col = 0; col < monitorTable.getModel().getColumnCount(); col++)
             column = monitorTable.getColumnModel().getColumn(col);
             column.setCellRenderer(new MonitorCellRenderer());
             column.setPreferredWidth(100);
             column.setResizable(false);
          }monitorTable is the JTable. This code is cribbed from the inital set up for the table, so is essentially what I want. What I have found is that these settings for the column are ignored, because if I change the preferred width, it does not change.
    I'm thinking that somehow my table ColumnModel reference is wrong, because it is referencing something else.
    Can anyone suggest what may be going wrong.
    Thanks

    This is all achieved by firing a fireTableStructureChanged() event.This causes the TableColumnModel to be recreated from scratch, therefore you lose renderers and editors that have manually been assigned to the table.
    So far I have some of the functionality working in that I can make the
    table display less columns. This is achieved by modifying the data
    stored in the TableModel. In fact what I do is re-create the Column Headers and data.Sounds unecessary to me. Just remove the TableColumn from the TableColumnModel and the table will be painted correctly. There is no need to play with the data in the TableModel.

  • Cell editor removed when table resized

    I'm using Java 1.5.0_06 in my application. I have a JFrame which contains a JTable. I use FormLayout (which is like GridBagLayout). When the frame resizes, the table resizes too.
    When I enter edit mode in a cell of the table and resize the frame (and the table), the cell exits edit mode. The editor of the cell is removed when the table is resized which causes the value that I had entered in the cell to be lost.
    Is there a way to stop cell editing when the frame is resized instead of the cell just exiting edit mode.
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import com.jgoodies.forms.factories.FormFactory;
    import com.jgoodies.forms.layout.CellConstraints;
    import com.jgoodies.forms.layout.ColumnSpec;
    import com.jgoodies.forms.layout.FormLayout;
    import com.jgoodies.forms.layout.RowSpec;
    public class ResizableTableTest extends JFrame {
         final JScrollPane _scrollPane;
         public static void main(String[] args) {
              ResizableTableTest frame = new ResizableTableTest();          
                frame.addWindowListener(new WindowAdapter() {
                     public void windowClosing(WindowEvent e) {
                          System.exit(0);
                frame.setSize(451, 340);
                frame.setVisible(true);
         public ResizableTableTest() {
              super();
              getContentPane().setLayout(new FormLayout(
                   new ColumnSpec[] {
                        new ColumnSpec("default:grow(1.0)"),
                        FormFactory.RELATED_GAP_COLSPEC,
                        FormFactory.DEFAULT_COLSPEC},
                   new RowSpec[] {
                        new RowSpec("default:grow(1.0)"),
                        FormFactory.RELATED_GAP_ROWSPEC,
                        FormFactory.DEFAULT_ROWSPEC,
                        FormFactory.RELATED_GAP_ROWSPEC,
                        FormFactory.DEFAULT_ROWSPEC,
                        FormFactory.RELATED_GAP_ROWSPEC,
                        FormFactory.DEFAULT_ROWSPEC,
                        FormFactory.RELATED_GAP_ROWSPEC,
                        FormFactory.DEFAULT_ROWSPEC}));
              _scrollPane = new JScrollPane();
              getContentPane().add(_scrollPane, new CellConstraints(1, 1, CellConstraints.FILL, CellConstraints.FILL));
              addTableToScrollPane();
         private void addTableToScrollPane() {
               JTable table = new JTable();
             DefaultTableModel model = (DefaultTableModel)table.getModel();
             table.setRowSelectionAllowed(false);
             table.setCellSelectionEnabled(true);
             //Add some columns
             model.addColumn("column A");
             model.addColumn("column B");
             model.addRow(new Object[]{"item1", "apple"});
             model.addRow(new Object[]{"item2", "banana"});
             model.addRow(new Object[]{"item3", "carrot"});
             model.addRow(new Object[]{"item1", "grape"});        
             _scrollPane.setViewportView(table);          
    }thanks,

    I would assume that on the resize of the table the
    editing cancelled event is being fired...
    You could try overriding the method in the JTable and
    when it gets fired, fire the editing stopped method
    instead... not sure whether that will work thoughI tried that, but it didn't help. On searching for this problem, I saw a bug report on this very problem.
    Here's info on a related bug in java:
    Cell editing does not complete when JTable loses focus
    Lost newly entered data in the cell when resizing column width
    And here's an interesting article:
    Why Editable Table Cells Are Evil
    Message was edited by:
    petes1234

  • Tab with Cellrenderer and Combobox

    When using Cellrenderer to display a combobox in a datagrid, there is an issue with using Tab. If you tab through the cells, it will cause the combobox to erase. To fix this the column needs to be set to non-editable. Problem with doing this is that then you cannot tab to the cell where the combobox is.
    Does anyone know a work-around this?

    Had you RTFA you would have learnt that JTable uses Renderers in the same way you would use a
    rubber stamp... thus each header is NOT a seperate Component, but the same component simply
    used to paint it....
    Following on from this... you may have now what looks very much like an active combo box, this is
    just fooling you. It is merely a ghost of a combo box.. some pixels on the screen, nothing more..
    First and foremost, before running around in desperate circles - RTFA

Maybe you are looking for

  • How can we increase the maximum number of records which we export from UME

    Hi All,          Is there any way to increase the maximum number of records which we can export from the UME. Please give your valuable suggestions as soon as possible. Thanks in Advance Regards, Ramalakshmi.S

  • Configuring Weblogic's jDriver for Oracle to use in distributed transactions

              Here is some errata to the instructions at "Configuring XA JDBC drivers" section of the online beta documentation:           http://www.weblogic.com/docs60/adminguide/managetx.html#1041268           The sample JDBC connection pool using Web

  • Why does the sound only work for certain programs?

    The sound is only working for certain programs on my iPad. Does anyone know why? Any help is appreciated.

  • Total assets in Final Cut Server

    is there a way to display how many assets are in a FCSvr database? I'm in the process of uploading over 10,000 assets to my server and want to be sure the server database asset quantity matches my storage disk quantity of original clips.

  • Bookmarks not visible... (end of a page)

    Hi, Let's suppose the heading where I want to create a bookmark is at the end of a page (page 142 for instance). When clicking on it, Adobe Acrobat 9 doesn't show the bookmark I created.... but it displays the page 143... I tried to right-clik on the