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.

Similar Messages

  • JTable custom cell renderer and editor breaks row sorting

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

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

  • Help with Custom Component: Ajax and ValueChangeListener

    Hello,
    I am trying to create a custom component that triggers an update via Ajax. However, I would also like to trigger a ValueChangeListener method from the same component, however I am unsure of how to obtain and trigger the ValueChangeEvent.
    The code I have so far in the Phase Listener is:
    private void handleAjaxRequest(PhaseEvent event) {
         FacesContext context = event.getFacesContext();
            HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
            Object object = context.getExternalContext().getRequest();
            if (!(object instanceof HttpServletRequest)) {
                return;
            HttpServletRequest request = (HttpServletRequest)object;
            HttpSession session =  request.getSession();
            String requestType = request.getParameter("jsflotRequestType");
            if (requestType != null && requestType.equalsIgnoreCase("jsflotchartValueChange")) {
                 //Trigger valueChangeEvents
                 log.info("Handling JSFlot Chart Value Change Event.");
    }What I am looking for though, is some information regarding how to obtain the ValueChangeListener from the request/session objects.
    The component tag is called like this:
    <jsflot:flotChart id="valueTimeChart"
         value="#{chartMbean.chartSeries}"
         valueChangeListener="#{chartMbean.valueChangeListener}"Any help would be greatly appreciated!

    The field calculation order was not in the correct order, had a devil of a time figuring out how to get to it, in Acrobat X.
    My check boxes for shipping have the same name field but I don't see a tab for export value for the check boxes, and I have no idea how to implement your suggestions for a switch or if statement or what fields to attach them to. 
    My amatuer attempt at a shipping formula follows, I don't know if I can use a range for event value, or where to put the script, if it is even correct.
    if(event.value == "<25.01")
        nShipFee = 06;
    else if(event.value == "25.01 - 75")
        nShipFee = 11.50;
    else if(event.value == "75.01 - 125")
        nShipFee = 15;
    else if(event.value == "125.01 - 200")
        nShipFee = 20;
    else if(event.value == "200.01 - 300")
        nShipFee = 25;
    else if(event.value == "300.01 - 400")
        nShipFee = 30;
    else if(event.value == ">400")
        nShipFee = 50;

  • Inconsistent behavior with Custom Cell Renderer

    I have two questions:
    Questions # 1.
    I have created a custom cell renderer for my JTable that changes color if the text property changes and the text contains the letter 'S'. Like
    so:
    class SchedRenderer extends DefaultTableCellRenderer{
    public SchedRenderer(){
    super();
    final Color c = scSelfCont.panelbg;
    this.setForeground(c);
    this.addPropertyChangeListener("text",new PropertyChangeListener(){
    public void propertyChange(PropertyChangeEvent e){
         boolean foundS=false;
         String text=e.getNewValue().toString();
         for(int i=0;i<text.length();i++)
         if(text.charAt(i)=='S'){
         foundS=true;
         break;
         if(foundS){
         SchedRenderer.this.setBackground(Color.red);
         SchedRenderer.this.setForeground(Color.red);
         else{
         SchedRenderer.this.setBackground(c);
         SchedRenderer.this.setForeground(c);
    99% of the time it works just fine. But occasionally the cell will revert back to its original color, and then back to the correct color after clicking somewhere entirely different. I set some breakpoints in the property change handler and it gets called quite frquently even if no change has been made. At first I thought this was a JDK bug, but I am now convinced that there simply must be a better way to do this, any ideas?
    Question # 2:
    Is there a simple way to change the color of an entire row without selecting it? Currently I am using Custom Cell Renderers to change
    colors of cells, but it seems like such an obtuse method. Is there a better way?
    Thanks in advance.
    Adrian Calvin

    I have two questions:
    Questions # 1.
    I have created a custom cell renderer for my JTable that changes color if the text property changes and the text contains the letter 'S'. Like
    so:
    class SchedRenderer extends DefaultTableCellRenderer{
      public SchedRenderer(){
        super();
        final Color c = scSelfCont.panelbg;
        this.setForeground(c);
        this.addPropertyChangeListener("text",new PropertyChangeListener(){
           public void propertyChange(PropertyChangeEvent e){
         boolean foundS=false;
         String text=e.getNewValue().toString();
         for(int i=0;i<text.length();i++)
           if(text.charAt(i)=='S'){
             foundS=true;
             break;
         if(foundS){
           SchedRenderer.this.setBackground(Color.red);
           SchedRenderer.this.setForeground(Color.red);
         else{
           SchedRenderer.this.setBackground(c);
             SchedRenderer.this.setForeground(c);
    [\code]
    99% of the time it works just fine.  But occasionally the cell will revert back to its original color, and then back to the correct color after clicking somewhere entirely different.  I set some breakpoints in the property change handler and it gets called quite frquently even if no change has been made.  At first I thought this was a JDK bug, but I am now convinced that there simply must be a better way to do this, any ideas? 
    Question # 2:
    Is there a simple way to change the color of an entire row without selecting it?  Currently I am using Custom Cell Renderers to change
    colors of cells, but it seems like such an obtuse method.  Is there a better way?
    Thanks in advance.
    Adrian Calvin

  • Help with opening Adobe Reader and downloading updates

    I can not open Adobe .pdf files any longer (this started yesterday, prior to that I could open adobe files).
    When I double click a .pdf file I get this notice on my screen: Windows cannot access the specified device path or file. You may not have the appropriate permission to access file.
    So I went to the Adobe download site to download a new copy of Adobe.  When I start the download I get this on the screen:  The instruction at "0x0e3a0068" referenced memory at "0x0e3a0068."  The memory could not be written.  Then two options are listed: click OK to terminate or cancel to debug.  So I click on cancel and I get this on my screen: Internet Explorer has closed this webpage to help protect your computer.   A malfunctioning or malicious addon has caused I.E. to close this webpage.
    I don't have AVG running, I do have avast but I've disabled it.  I ran Registry Mechanic and an I.E. erasure program but nothing helps.
    I have gone into I.E. and reduced the security level to its lowest state but no joy.
    So, any ideas or suggestions on what's the problem and how to overcome it would be appreciated.  Thanks, in advance, for your reply.  Jim R.

    Hi Mike..tried that as well but no joy.  A friend of mine was looking at it all and noticed that it was an I.E. thing as far as not letting me redownload the reader so I went to Mozilla Firefox and I could download a new version but....whenever I attempt to open a .pdf file I get that message, "Windows can not open the specified device, path or file. You man not have the appropriate permissions to access the item." 
    Damn...this is irritating as I need to get to some of thos files as I need them for a Journal I'm working on as editor-in-chief. 
    It all worked just fine last Saturday but starting Monday when I was on my flight out to D.C.  no joy. 
    Sigh...Jim R.
    Jim R.
    Date: Tue, 1 Dec 2009 14:50:27 -0700
    From: [email protected]
    To: [email protected]
    Subject: Help with opening Adobe Reader and downloading updates
    Under the help menu, there is an option to repair the installation of reader. Did you try that?
    >

  • Help with custom tables

    Hello All,
    I need some help with custom tables. I have created a custom table to maintain names and I also did table maintenance generation so that the user can maintain names in this table using SM30 transaction.
    The question is, in my program on the selection screen when the user press F4 I need to display the values maintained in this custom table...
    Can anyone help me with this.
    Thanks
    Pavan

    If I understood you correctly, you have a program in which one or some of the selection screen fields refer to a custom database table field(s).
    You want to implement a F4 functionality.
    Fill an internal table with the values you want to show.
    Call the function module 'F4IF_INT_TABLE_VALUE_REQUEST' in the event AT SELECTION-SCREEN ON VALUE-REQUEST FOR MYPARAM as follows.
    call function 'F4IF_INT_TABLE_VALUE_REQUEST'
           exporting
                retfield    = MYITAB-FIELD
                dynprofield = MYSELSCREENPARAM
                dynpprog    = sy-cprog
                dynpnr      = sy-dynnr
                value_org   = 'S'
           tables
                value_tab   = my_f4_itab.
    Srinivas

  • Need help with my iPhone 5 and my Macbook Pro.

    Need help with my iPhone 5 and my Macbook Pro.  I was purchased some music on itunes at my mac. Some reason I deleted those music from both on Mac and iPhone 5.  Today, I went to my iPhone iTunes store inside of iCloud to redownload my puchased. But those song won't able to sync back to my iTunes library on my Mac.  Can anyone help me with that ??....
    iPhone 5, iOS 6.0.1

    You've posted to the iTunes Match forum, which your question does not appear to be related to. You'll get better support responses by posting to either the iTunes for Mac or iTunes for Windows forum. Which ever is more appropriate for your situation.

  • Barbara Brundage, can you help with PS Elements 11 and Epson R2000 printer issue?

    Seeking help with PS Elements 11 which does not work with Epson r2000 printer.  Epson tech support could not fix, said it is PS e11 problem.  Receive prompt on PS e11 screen when I try to print stating "not compatible or settings are not correct.  Have set PS to manage color and printer manages color to off.  Would appreciate any suggestions.  Thank you.

    Hi,
    Sincerely appreciate your help.  Running Windows 7 on a  Dell XPS420.  System has been very stable for years.  Before purchasing the Epson r2000, I owned an r1800 which was an excellent printer but after seven years started to exhibit paper feed problems.  The r1800 worked with all applications and I was well satisfied with the saturation, contrast, etc. printing mostly 8x10 and 11x17 prints. 
    Thank you for the information about the # of installs for PS E11, will try uninstall/reinstall this morning.
    Will let you know how things go.
    Richard
    Date: Thu, 12 Sep 2013 19:47:38 -0700
    From: [email protected]
    To: [email protected]
    Subject: Barbara Brundage, can you help with PS Elements 11 and Epson R2000 printer issue?
        Re: Barbara Brundage, can you help with PS Elements 11 and Epson R2000 printer issue?
        created by Barbara B. in Photoshop Elements - View the full discussion
    What operating system are you using?
         Please note that the Adobe Forums do not accept email attachments. If you want to embed a screen image in your message please visit the thread in the forum to embed the image at http://forums.adobe.com/message/5678022#5678022
         Replies to this message go to everyone subscribed to this thread, not directly to the person who posted the message. To post a reply, either reply to this email or visit the message page: http://forums.adobe.com/message/5678022#5678022
         To unsubscribe from this thread, please visit the message page at http://forums.adobe.com/message/5678022#5678022. In the Actions box on the right, click the Stop Email Notifications link.
         Start a new discussion in Photoshop Elements by email or at Adobe Community
      For more information about maintaining your forum email notifications please go to http://forums.adobe.com/message/2936746#2936746.

  • Installed my Photoshop Elements 7 on my new laptop.  Says my serial number is invalid.  Chatted with customer service rep and she says the number should work. What now?

    Installed my Photoshop Elements 7 on my new laptop.  Says my serial number is invalid.  Chatted with customer service rep and she says the number should work. What now?

    Hi,
    Did the serial number come from a boxed set and previously installed from disc and are you now trying to install from a download?
    If so, that will not work - the serial numbers are different.
    If you don't have a dvd drive on your new system, perhaps you could get someone to copy your disc to a memory stick and install from that.
    Brian

  • Renderers and Editors

    Can anyone please send me some tutorial links to understand the concept of Renderers and Editors in Java Swing.

    A good starting point is [url http://java.sun.com/docs/books/tutorial/uiswing/components/components.html]here. Lists, combo boxes, tables and trees all have renderers/editors so follow the link for the appropriate component.

  • New help with my mac air and airport extreme time capsule dont know how to save to time capsule and use as a external hd

    new help with my mac air and airport extreme time capsule dont know how to save to time capsule and use as a external hd would like 2 store my home videos and pictures on the time machine (ONLY) as the MAC AIR has storage space limited space please help. THANK YOU.

    See the info here about sharing or using the TC for data.
    Q3 http://pondini.org/TM/Time_Capsule.html
    It is extremely important you realise.. the Time Capsule was never designed for this.
    It is a backup target for Time Machine.. that is the software on the computer that does backups.. it has no direct connection to the Time Capsule.
    It has no ability to back itself up.. unlike all other NAS in the market. It is therefore likely one day you will lose all your files unless you seriously work out how to backup.
    The TC is slow to spin up the hard disk and fast to spin down. iTunes and iPhoto will continually lose connection to their respective libraries.
    iPhoto in particular is easy to corrupt when you move photos over wireless into the library.. once corrupted all is corrupt. A single photo will ruin it all.. so backup is utterly essential.
    Time Machine cannot do backups of network drives. ie the TC. You will need a different backup software like CCC. You will then need another target to backup to..

  • Problem sorting JTable with custom cell editor

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

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

  • Size of combobox in JTable with custom cell editor

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

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

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • Custom Cell Renderer and JTable

    Hello all,
    here is what i am trying to do. i want that when a user clicks on a cell the
    color of the cell should change to say red. when the user clicks on the other
    cell the red color in the first cell should remain.
    the way i am trying do to this is by making an object which contains an on and
    off state. based on click ie valuechanged() method in table
    based on the row and column i change the value of the boolean state on. my
    custom cell renderer checks whether the state is on or off
    and then changes the color.
    rightnow I am able to change the color on click but am unable to retain the
    color. so how can i retain the color.
    // making table
              vectorForSingleRow.add(0, "");                    
              vectorForSingleRow.add(1, new CellColorObject(TEXT_EDITOR));     
              Vector tempVectorForSingleRow = new Vector(vectorForSingleRow);               
              tempVectorForSingleRow.set(0, name);     
              vectorForSingleRow.set(1, new CellColorObject(TEXT_EDITOR));          
              data.add( tempVectorForSingleRow ); // data is a vector
              myTableModel = new DefaultTableModel(data, columnNames)
              //Customrenderer
              public Component getTableCellRendererComponent(JTable table, Object value,      
                                                     boolean isSelected, boolean hasFocus, int row, int column) {
              CellColorObject myObj = (CellColorObject)value;
              this.setText(value.toString());
                   System.out.println("value.getClickedStatus() " + myObj.getClickedState());
                   if(myObj.getClickedState()){
                        System.out.println("in 2");     
                        this.setBackground(Color.PINK);
                   if(isSelected){
                   System.out.println("in 1");
                   this.setSelected(true);
    // other things and end of method
    //custom object for storing state of the cell                                   
    public class CellColorObject{
         private String name = "";
         private boolean clickedState = false;
         public CellColorObject(String incomingName){
              name = incomingName;
         public void setClickedState(boolean newClickedState){
         System.out.println("setClickedState");
              clickedState = newClickedState;
         public boolean getClickedState(){
         System.out.println("getClickedState()");
              return clickedState;
         public String toString(){
              return name;
    // valueChanged method
           public void valueChanged(ListSelectionEvent e) {
             if (e.getValueIsAdjusting()) return;
              if(column == 1){
                   CellColorObject tempObj = (CellColorObject) myTable.getValueAt(row,column);
                   tempObj.setClickedState(true);
                   myTable.setValueAt(tempObj, row, column);
    // other things and method end
              

    You problem is that you are NOT setting the clickedState of your object:
    public Component getTableCellRendererComponent(JTable table, Object value,                                                       boolean isSelected, boolean hasFocus, int row, int column) {                         CellColorObject myObj = (CellColorObject)value;          this.setText(value.toString());                         System.out.println("value.getClickedStatus() " + myObj.getClickedState());               if(myObj.getClickedState()){                    System.out.println("in 2");                         this.setBackground(Color.PINK);               }               if(isSelected){               System.out.println("in 1");               this.setSelected(true);In the above, you have
    if (myObject.getClickedState())
    /// do code..
    notice you have:
    if (isSelected)
    this.setSelected(true);
    Maybe I am missing something, but I see no code that sets your objects clicked state when selected. My guess is that you should be doing value.setClickedState(true) when the thing is selected, something like:
    CellColorObject myObj = (CellColorObject)value;
    if (isSelected)
    myObj.setClickedState(true);
    else
    myObj.setClickedState(false);
    BUT, you didn't finish your code snippet within the method there, so perhaps you do this already?
    What you have should almost work, in that every single cell will call this method and if the object's clickedState is true, it should set the background color. Just make sure you are setting the objects clicked state.

Maybe you are looking for

  • Editing tags in Editor view

    I am using Elements 4.0 and have added tags (keywords)to several shots in the Organizer view. It has become necessary to remove some of the tags associated with the shots and I have done that by right clicking and selecting remove tags and removing n

  • Opening RAW files with Bridge CS3

    When I try to open a RAW file from Bridge CS3 it defaults to Mac Preview and does not open Photoshop Elements 6 RAW converter.  If I open a RAW file outside of Bridge it work fine.  What did I do wrong??   Using a iBook G4 with OS 10.5.8 and Photosho

  • Live Upgrade from 8 to 10 keeping Oracle install

    Hi everyone, I'm trying to figure out how to do a Live Upgrade from Solaris 8 (SPARC) to 10 and still keep my Oracle available after the reboot. Since all of the Oracle datafiles are on /un or /opt/oracle I figure I can just create a new BE for /, /e

  • Budget Report for Project does not work

    Can somone help make sense of this inbuilt report ; Fnancial Reports/Budget Reports/Budget Report - on the Selection Criteria I put under Project - MO project. The result is the Report is that it Shows me the ACTUAL sales for MO project but the BUDGE

  • Printing becoming faint

    HP LaserJet P1102W Printing has recently become faint – not in lines but general faint all over.  In the past I thought I received a warning informing how many copies to go before the cartridge was empty.  To date I have received no warning.  The pri