Refreshing renderer in jtable

hi all,
i am using JLabel for rendering a JTable, but the problem is
JTable is not refreshing properly.
import java.awt.Component;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
public class SampleTable extends JFrame
    public SampleTable()
        Container container = getContentPane();
        container.add(getHtmlTable());
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    private JScrollPane getHtmlTable()
        Object[] tblColHeaders = {"a","b"};
        Object[][] tradedata = {
                {"<HTML><table >"
                 + "<tr><td >row 1, cell 1</td></tr></table></HTML>", "<HTML><table>"
                       + "<tr><td>row 1, cell 1</td></tr><tr><td>row 1, cell 2</td></tr></tr><tr><td>row 1, cell 2</td></tr>"
                       + "</table></HTML>"},
                { "<HTML><table >"
                 + "<tr><td >row 1, cell 1</td></tr>"
                 + "</table></HTML>", "<HTML><table>"
                       + "<tr><td>row 1, cell 1</td></tr><tr><td>row 1, cell 2</td></tr></tr><tr><td>row 1, cell 2</td></tr>"
                       + "</table></HTML>"},
                { "<HTML><table >"
                 + "<tr><td >row 1, cell 1</td></tr>"
                 + "</table></HTML>", "<HTML><table>"
                       + "<tr><td>row 1, cell 1</td>/tr><tr><td>row 1, cell 2</td></tr></tr><tr><td>row 1, cell 2</td></tr>"
                       + "</table></HTML>"}};
        JTable table = new JTable(tradedata,tblColHeaders){
            public boolean isCellEditable(int row,int col){
                return false;
        table.setDefaultRenderer(Object.class,new MyTableCellRenderer());
        JScrollPane scrTabel = new JScrollPane(table);
        return scrTabel;
    public class MyTableCellRenderer extends JLabel implements TableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus,
                                                       int rowIndex, int vColIndex)
            setText(value.toString());
            setSize(table.getColumnModel().getColumn(vColIndex).getWidth(),
                    getPreferredSize().height);
            if (table.getRowHeight(rowIndex) != getPreferredSize().height)
                table.setRowHeight(rowIndex, getPreferredSize().height);
            if(isSelected){
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            return this;
    public static void main(String[] args)
        new SampleTable();
}thanks
daya

1) Your renderer is in an infinite loop because column one need a row height of 16, so you change the height, but column two need a row height of 48, so you change the height.
But whenever you change the row height the table needs to render the entire row, so it tries to render column 1 again and it resets the height, then column 2 and it resets the height etc, etc.
2) All you want you renderer to do is change the height, so don't create the renderer from scratch. That is don't extend JLabel, extend DefaultTableCellRenderer so you don't need to add all the custom code.
Your renderer should be something like this:
    public class MyTableCellRenderer extends DefaultTableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus,
                                                       int rowIndex, int vColIndex)
            super.getTableCellRendererComponent(table,
                value, isSelected, hasFocus, rowIndex, vColIndex);
            if (table.getRowHeight(rowIndex) < getPreferredSize().height)
                table.setRowHeight(rowIndex, getPreferredSize().height);
            return this;
    }

Similar Messages

  • Align for multi-header renderer in JTable

    Hi,
    I have a question about multi-header renderer in JTable. Here is the problem, please help me:
    I used the MultiLineHeaderRenderer class example from
    http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html
    This example makes the header to be centered (as setHorizontalAlignment(JLabel.CENTER)). Also, it is for the all the headers with 2 lines (i don't know how to describe it).
    In my project, I have just a few header with 2 lines, most of them are one line. By using this example renderer class, I have the header height is bigger, of course because of some 2 lines headers, and one line header is automatically set as the TOP. What I want is to make one line header to be set as the BOTTOM just like in EXCEL.
    Please help me, sorry for my technical explaination (poor huh?)
    Thanks in advance.

    If I understand correctly just put a space then a new line before your text for your cell that you want the text at the bottom.
    like this: " \nBottom Text"
    You'll need the leading space because of how StringTokenizer works.

  • Help required for creating Row Renderer for JTable

    Hi all,
    I am trying to create customize row renderer for JTable.
    My requirements are as below.
    |-----------------|-------------------|------------------|------------------|-------|----------------|
    |Category | Product ID |Description | Unit Price |Qty | Sub-Total |
    |-----------------|-------------------|------------------|------------------|-------|----------------|
    I have designed a combobox for category and product ID columns inside JTable. I want to put a listener on Category ID such that product IDs in selected categories will be visible in product ID drop down of selected row keeping other rows unchanged.
    Column renderer is defining a class for entire column but by setting that im getting same values in all the rows for product IDs. And if I update values for one product ID dropdown, entire column data is changing.
    Even im not able to put array of combobox for product ID column as number of rows are not fixed and increasing runtime.
    Can anyone suggest me how can i customize Cells under particular column with JComboBox?
    Regards,
    Mahesh Kedari
    Fidus Technologies Ltd.
    Edited by: m1JustM1 on Feb 8, 2010 4:48 AM

    Start by reading [this |http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#editrender] tutorial. If you still have questions afterward, feel free to post an SSCCE .

  • Refresh data in JTable

    hi, i hava a problem, i have a jtable where same Data column depend from another column of the same jtable and a jtextfield that is external to jtable
    my jtable is
    jcombobox | text | text | text ecc....
    when the user change the SelectedItem of jcombobox the other column`s data is jacombobox values * external JtextField text....
    if i change the value of the external jtextfield how can i refresh the data in the jtable whitout click over all cell???
    this is the code of the My CellRender of the first column:
    public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
        JTable jt;
        PortataUgelli pug;
        public MyComboBoxRenderer(String[] items,JTable table,PortataUgelli pu) {
            super(items);
            this.jt=table;
            this.pug=pu;
            addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt){
                    if (jt.getSelectedColumn()==0){ //This action is only for the first column
                        String ugello= (String)getSelectedItem();
                        if (ugello==null) ugello=""+0;
                        double b=Double.parseDouble(pug.getPressione().trim());
                        String par="" + new VariID().getFunzioneUgelli(ugello,b); //this method calculate the value of the other cell
                        int sel;
                        if (jt.getSelectedRow() < 0) sel=0;
                        else sel = jt.getSelectedRow();
                        jt.setValueAt(par,sel,1); //set the value of the cell
        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {
            if (isSelected) {
                setForeground(table.getSelectionForeground());
                super.setBackground(table.getSelectionBackground());
            } else {
                setForeground(table.getForeground());
                setBackground(table.getBackground());
            // Select the current value
            setSelectedItem(value);
            return this;
    }

    It's fairly simple...
    you need to have your own custom TableModel. Extend AbstractTableModel and when you go to set a cell (to change the data in that cell) you simply fire an event with the:
    fireTableCellUpdated(int row, int column) method to let the view know that the data changed in that cell of that table changed and needs to be redrawn...
    Here's the link to the tutorial page/section on creating a custom table model and also firing events when data changes:
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data

  • COMBOBOX & CHECKBOX RENDERER IN JTABLE

    Hi,
    I created JXTable by using swingx palette in Netbeans IDE. In two columns of my table, for each row I want to put checkboxes and comboboxes. I searched the ways on internet and I finalise my code. However, because I used cell editor, I just see my checkboxes and comboboxes when I enter a specific cell. I read all tutorials but unfortunately I cannot learn how to use renderer to show comboboxes and checkboxes all the time. In below you could check my code and if possible please teach how to use renderers and try to give feedback to my code by fixing it. Thank you.
    *(P.S Please don't send any web site for tutorial, i searched almost all of them; but I can't understand the logic of it.)*
    // SET UP THE COMBO BOX
    public void setUpOverwriteValueColumn(JXTable table, TableColumn overwriteValCol) {
    valueCombo = new JComboBox();
    Field field = new Field();
    ArrayList values = new ArrayList();
    values = field.getValues();
    for(String a:values){
    valueCombo.addItem(a);
    overwriteValCol.setCellEditor(new DefaultCellEditor(valueCombo));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    overwriteValCol.setCellRenderer(renderer);
    // SET UP THE CHECK BOX
    public void setUpOverwriteColumn(JXTable table, TableColumn overwriteCol) {
    valueChk = new JCheckBox();
    overwriteCol.setCellEditor(new DefaultCellEditor(valueChk));
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for check box");
    overwriteCol.setCellRenderer(renderer);
    setUpOverwriteColumn(monitorTable, monitorTable.getColumnModel().getColumn(3)); //add checkbox to 3rd column
    setUpOverwriteValueColumn(monitorTable, monitorTable.getColumnModel().getColumn(4)); //add combobox to 4th column

    Finally I can add renderers. But, now I have different question. When user clicks on the checkbox I want to enable the combo box. I mean if user clicks the checkbox in row 3; only the combo box which placed in row 3 should be enabled; other combos in other rows should not be enabled. Please help if you know the answer. Here is my code:
    public class ComboBoxRenderer extends JComboBox implements TableCellRenderer{
        public ComboBoxRenderer(Vector items) {
            super(items);
            setOpaque(false);
        public Component getTableCellRendererComponent(
                                                    JTable table,
                                                    Object value,
                                                    boolean isSelected,
                                                    boolean hasFocus,
                                                    int row,
                                                    int column){
            if (isSelected && !hasFocus){
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            }else{
                setBackground(table.getBackground());
                setForeground(table.getForeground());
              setSelectedItem(value);
            return this;
    public class CheckBoxRenderer extends JCheckBox implements TableCellRenderer
      public CheckBoxRenderer() {
        setOpaque(false);
        setHorizontalAlignment(CENTER);
        setVerticalAlignment(CENTER);
      public Component getTableCellRendererComponent(
                                                        JTable table,
                                                        Object value,
                                                        boolean isSelected,
                                                        boolean hasFocus,
                                                        int row,
                                                        int column) {
        if (value != null) {
          this.setSelected( ( (Boolean) value).booleanValue());
        return this;
    }To show:
    public void setUpOverwriteValueColumn(JXTable table,
                                     TableColumn overwriteValCol) {
            Vector v = new Vector();
            Field field = new Field();
                ArrayList <String> values = new ArrayList<String>();
                values = field.getValues();
                for(String a:values){
                    v.addElement(a);
                ComboBoxRenderer renderer = new ComboBoxRenderer(v);
                overwriteValCol.setCellRenderer(renderer);
        // SET UP THE CHECK BOX
        public void setUpOverwriteColumn(JXTable table, TableColumn overwriteCol) {
                CheckBoxRenderer renderer = new CheckBoxRenderer();
                overwriteCol.setCellRenderer(renderer);
        }Edited by: duygu_simsek on Jun 18, 2009 11:27 AM

  • Combobox Renderer in JTable

    Can someone please post code showing me how to make a renderer that would indicate a combobox in a JTable? I already have the combobox editor there, but I want the renderer to show a small down arrow, indicating to the user that the cell is a combobox.
    Thanks!

    public class ComboBoxRenderer extends JComboBox implements TableCellRenderer{
        public ComboBoxRenderer(Vector items) {
            super(items);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column){
            if (isSelected && !hasFocus){
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            }else{
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            setSelectedItem(value);
            return this;
    [/code[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • JSlider renderer in JTable

    Hi,
    I insert JSlider in a column of a JTable, redefining renderer and editor. The problem is that when I resized the size of the JTable (or the column with the sliders), the sliders are not resized. They are only resized if I move another window over them. Is is a repaint I have to apply ? The problem is that I do not know where to apply it.
    This is my code: I put only the JTable and the renderer, not the editor and the other components.
    This is the JTable (with a main to launch it)
    import GUI.TimeView.CategoryTimeDimensionView;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    public class TableDialogEditDemo extends JPanel {
        private boolean DEBUG = false;
        JTable table;
        public TableDialogEditDemo() {
            super(new GridLayout(1,0));
            table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(200, 48));
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
            table.getColumnModel().getColumn(0).setResizable(false);
            table.getColumnModel().getColumn(0).setPreferredWidth(80);
            table.getColumnModel().getColumn(1).setResizable(false);
            table.getColumnModel().getColumn(1).setPreferredWidth(80);
            table.getColumnModel().getColumn(2).setCellRenderer(new SliderRenderer());
            table.getTableHeader().setReorderingAllowed(false);
            //Add the scroll pane to this panel.
            add(scrollPane);
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"Curve", "Color", "Transparency", "Displayed"};
            private Object[][] data = {
                {"Average", Color.black, 70, new Boolean(false)},
                {"Minimum", Color.black, 70, new Boolean(false)},
                {"Maximum", Color.black, 70, new Boolean(false)}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 1) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                if (DEBUG) {
                    System.out.println("Setting value at " + row + "," + col
                            + " to " + value
                            + " (an instance of "
                            + value.getClass() + ")");
                data[row][col] = value;
                fireTableCellUpdated(row, col);
                if (DEBUG) {
                    System.out.println("New value of data:");
                    printDebugData();
            private void printDebugData() {
                int numRows = getRowCount();
                int numCols = getColumnCount();
                for (int i=0; i < numRows; i++) {
                    System.out.print("    row " + i + ":");
                    for (int j=0; j < numCols; j++) {
                        System.out.print("  " + data[i][j]);
                    System.out.println();
                System.out.println("--------------------------");
            private Object[] longValues;
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("TableDialogEditDemo");
            frame.setDefaultCloseOperation(JFra
            JComponent newContentPane = new TableDialogEditDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }and the renderer:
    mport java.awt.Color;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    import java.awt.Component;
    import javax.swing.BorderFactory;
    import javax.swing.JSlider;
    import javax.swing.border.Border;
    public class SliderRenderer extends JSlider implements TableCellRenderer {
        Border unselectedBorder = null;
        Border selectedBorder = null;
        public SliderRenderer() {
            setMinimum(0);
            setMaximum(100);
            setBackground(Color.white);
            setBounds(0, 0, 100, 10);
            setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object val, boolean isSelected, boolean hasFocus, int row, int column) {
                if (isSelected) {
                    if (selectedBorder == null) {
                        selectedBorder = BorderFactory.createMatteBorder(1,3,1,3, table.getSelectionBackground());
                    setBorder(selectedBorder);
                } else {
                    if (unselectedBorder == null) {
                        unselectedBorder = BorderFactory.createMatteBorder(1,3,1,3, table.getBackground());
                    setBorder(unselectedBorder);
            int value = (Integer) val;
            setValue(value);
            return this;
    }Thank you for your answers.

    Thank you for your answers,
    blackbug wrote:
    why did you assign a default position and size for your slider.
    try to remove the default size. or the setBounds property.It was something I forgot. I removed it, but it does not change anything.
    Olek wrote:
    Try to use revalidate() or validate() with the sliders after resizing the panel.I had to the table the listener:
    addComponentListener(new java.awt.event.ComponentAdapter() {
                public void componentResized(java.awt.event.ComponentEvent evt) {
                 //table.getColumnModel().getColumn(2).getCellRenderer().getTableCellRendererComponent(table, 70, false, false, 0, 2).validate();
            });but I do not know how to apply the validate() methode: how can I find the slider?
    With table.getColumnModel().getColumn(2).getCellRenderer().getTableCellRendererComponent(table, 70, false, false, 0, 2) ?

  • JFormattedTextField as custom cell renderer in JTable?

    I have my custom renderers in my custom JTable that work quite good so far. After upgrading to JDK 1.4, i want to finally use formatted text fields in my JTable. So, i extended my renderes to also support formatters. But this doesn't seem to work. The formatter of my DateRenderer's constructor is used. When i try to change it via my JTable's custom method
         * Set formatter for a column. The formatter is only used if a corresponding renderer is set up (see configColumn()).
         * @param columnIndex Index of colum (0 = first column).
         * @param formatter Formatter to set.
         * @return TableColumn object for given index or null.
        public TableColumn setFormatter(int columnIndex, AbstractFormatter formatter) {
            TableColumn result = null;
            if (columnIndex >= 0 && columnIndex < getColumnCount()) {
                result = getColumnModel().getColumn(columnIndex);
                TableCellRenderer tcr = result.getCellRenderer();
                if (tcr instanceof DateRenderer) {
                    DateRenderer dr = (DateRenderer) tcr;
    System.out.println("setFormatter("+columnIndex+","+formatter+")...");
                    dr.setFormatter(formatter);
                }//else: todo
            }//else: columnIndex invalid
            return result;
        }//setFormatter()that has a different formatter, it is not changed!

    Instead of using setFormatter(), i wrote my own set method:
         * Set DateFormat.
         * @param format DateFormat to set.
        public void setFormat(DateFormat format) {
            setFormatterFactory(new DefaultFormatterFactory(new DateFormatter(format)));
        }//setFormat()

  • Custom Cell Renderer for JTable

    Help, I'm trying to write a custom renderer for a column of my JTable but can't get it to work.
    Want I want is a cell in that column to be a label with an Icon and text.
    Trying to test with something simple, just changing colors but even that doesn't work. Can anyone see where I've gone wrong.
    table = new JTable(tableModel);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setShowGrid(false);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellRenderer(new DefaultTableCellRenderer() {
       public Component getTableCellRendererComponent(JTable table,
                                                   Object value,
                                                   boolean isSelected,
                                                   boolean hasFocus,
                                                   int row,
                                                   int column)
             JLabel label = (JLabel)
                super.getTableCellRendererComponent
                   (table, value, isSelected, hasFocus, row, column);
                label.setForeground(Color.red);
                label.setBackground(Color.black);
                System.out.println("Object: "+ value);
                return label;
    });Thanks,
    Derek

    Hi
    For colors try :
    all your code
    but where you call super.getTableCellRendererComponent(......
    do only setText(value.toString());
    I supose it is Ok just for changing the colors. If you want render
    an Icon plus some text you can put at your model a JLabel and at this
    render do
    setText((JLabel)value.getText());
    setIcon((JLabel)value.getIcon());
    inside a try/catch clause becasue you can put other kind of object at
    model level
    Or pass instances of an special Class with Icon/Text with publics members set/get to acces to text/icon.
    Hope this help

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

  • Cell rendering in JTable

    Can someone show me how to render the cells of a table column as a combo box and the cells of another table column as a check box.
    thx.

    Hi,
    You can easily get the checkbox as the renderer by implementing the getColumnClass(int columnIndex). But the catch is that your checkbox-column should return Boolean as its class. Check for that. That can only be the problem. Otherwise, it should work fine.
    public Class getColumnClass(int column) {
        switch(column) {
            case 1 :
                /* Assume that this is the column for which the checkbox
                 * rendering has to take place.
                return Boolean.class;
                break;
            case 2 :
                //Return the datatype of this column, say it is a Number
                return Number.class;
                break;
            //Your other cases would go here
            default :
                return String.class;
                break;
    }I hope that your problem is solved now. If not, there is another way by which you can explicitlt set the renderer of your column. In this case, there is no need to implement the getColumnClass() method. Here is the CheckBoxCellRender class...
    class CheckBoxCellRenderer extends JCheckBox implements TableCellRenderer
        public CheckBoxCellRenderer() {
            setHorizontalAlignment(JLabel.CENTER);
        }//constructor
        public Component getTableCellRendererComponent(JTable table, Object value,
                               boolean isSelected, boolean hasFocus, int row, int column) {
        if (isSelected) {
            setForeground(table.getSelectionForeground());
            super.setBackground(table.getSelectionBackground());
        else {
            setForeground(table.getForeground());
            setBackground(table.getBackground());
            setSelected((value != null && ((Boolean)value).booleanValue()));
            return this;
        }//getTableCellRendererComponent
    }Put this class as an inner class somewhere in your code, and then explicitly set this class as the column's default renderer. Here is how you can do it.
    myTable.getColumn("myCheckboxColumn").setCellRenderer(new CheckBoxCellRenderer());

  • How to set cell background color for JCheckBox renderer in JTable?

    I need to display table one row with white color and another row with customized color.
    But Boolean column cannot set color background color.
    Here is my codes.
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.TreeSet;
    public class BooleanTable extends JFrame
        Object[][] data = {{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE},{Boolean.TRUE}};
        String[] header = {"CheckBoxes"};
        public BooleanTable()
            setDefaultCloseOperation( EXIT_ON_CLOSE );
            TableModel model = new AbstractTableModel()
                public String getColumnName(int column)
                    return header[column].toString();
                public int getRowCount()
                    return data.length;
                public int getColumnCount()
                    return header.length;
                public Class getColumnClass(int columnIndex)
                    return( data[0][columnIndex].getClass() );
                public Object getValueAt(int row, int col)
                    return data[row][col];
                public boolean isCellEditable(int row, int column)
                    return true;
                public void setValueAt(Object value, int row, int col)
                    data[row][col] = value;
                    fireTableCellUpdated(row, col);
            JTable table = new JTable(model);
            table.setDefaultRenderer( Boolean.class, new MyCellRenderer() );
            getContentPane().add( new JScrollPane( table ) );
            pack();
            setLocationRelativeTo( null );
            setVisible( true );
        public static void main( String[] a )
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch( Exception e )
            new BooleanTable();
        private class MyCellRenderer extends JCheckBox implements TableCellRenderer
            public MyCellRenderer()
                super();
                setHorizontalAlignment(SwingConstants.CENTER);
            public Component getTableCellRendererComponent(JTable
                                                           table, Object value, boolean isSelected, boolean
                                                           hasFocus, int row, int column)
                if (isSelected) {
                   setForeground(Color.white);
                   setBackground(Color.black);
                } else {
                   setForeground(Color.black);
                   if (row % 2 == 0) {
                      setBackground(Color.white);
                   } else {
                      setBackground(new Color(239, 245, 217));
                setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
             return this;
    }

    Instead of extending JCheckBox, extend JPanel... put a checkbox in it. (border layout center).
    Or better yet, don't extend any gui component. This keeps things very clean. Don't extend a gui component unless you have no other choice.
    private class MyCellRenderer implements TableCellRenderer {
        private JPanel    _panel = null;
        private JCheckBox _checkBox = null;
        public MyCellRenderer() {
            //  Create & configure the gui components we need
            _panel = new JPanel( new BorderLayout() );
            _checkBox = new JCheckBox();
            _checkBox.setHorizontalAlignment( SwingConstants.CENTER );
            // Layout the gui
            _panel.add( _checkBox, BorderLayout.CENTER );
        public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
            if( isSelected ) {
               _checkBox.setForeground(Color.white);
               _panel.setBackground(Color.black);
            } else {
               _checkBox.setForeground(Color.black);
               if( row % 2 == 0 ) {
                  _panel.setBackground(Color.white);
               } else {
                  _panel.setBackground(new Color(239, 245, 217));
            _checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
            return _panel;
    }

  • How to use a JTextField as CellEditor and Renderer in JTable

    Hi, I want to use a JTextField as a CellEditor and CellRenderer in an JTable. How can I do this?
    Thanks for your help.

    For using JTextField as a CellEditor in JTable...try as directed below:
    TableColumnModel tcm = table.getColumnModel();
    JTextField txt = new JTextField();
    /***now specify the column number in which u want to add this textfield, e.g in the example below iam adding this textfield to 1st column***/
    tcm.getColumn(0).setCellEditor(new DefaultCellEditor(qty));
    Rajat.

  • Rendering a JTable within a JTable Cell

    How can one render a JTable within another JTable cell?

    You could return JTable in your TableCellRenderer.
    Denis Krukovsky
    http://sourceforge.net/projects/dotuseful/

  • Rendering a JTable

    is it possible to render a specific row (not cell, i know how to do that) in a JTable?

    You mean you can use a TableCellRenderer to render a cell? If that's what you know how to do, why can't you use the same object to render all the cells in a row the same way? Or perhaps you could explain your question.

Maybe you are looking for