Table Cell Renderer Text Alignment Problem

Hallo !
I got a JTable with cells containing text and icons. I would like to have the icon on the top and the text on the bottom, but the renderer aligns always the text on the right of the icon.
I made a custom renderer extending DefaultTableCellRenderer and there i wrote setVerticalTextPosition(BOTTOM);, but it does'nt work in any way (i tried in many ways. I also used html for the text, but it's the same).
More exactly the code is
public class MyRenderer extends DefaultTableCellRenderer{
public java.awt.Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
        super.getTableCellRendererComponent(table,""/*value*/,isSelected,hasFocus,row,column);
FieldRenderer renderedValue=(FieldRenderer)value;
//setHorizontalAlignment(CENTER);
//setVerticalAlignment(CENTER);
setVerticalTextPosition(BOTTOM);
setText(renderedValue.getRepresentation());
setToolTipText(renderedValue.getRepresentation());
setIcon(renderedValue.getIcon());
        return this;
}where FieldRenderer is an object containing icon, text, etc.
Can anyone help ?
Thanks in advance, Massimo
}

Setting a renderer for first column:
assetTable.getColumnModel().getColumn(1).setRenderer(tableRenderer);Your custom renderer must honor the selection color and border or otherwise the first column will not look selected. You should subclass DefaultTableCellRenderer:
public class AssesTableRenderer extends DefaultTableCellRenderer  {
  public Component getTableCellRendererComponent(...) {
    // default renderer uses a label
    JLabel label = (JLabel)super.getTableCellRendererComponent(...);
    // decide icon to use
    Icon icon = ...;
    label.setIcon(icon);
   return label;
}

Similar Messages

  • Setting Table Cell Renderer for a row or cell

    I need to make a JTable that has the following formats:
    Row 1 = number with no decimals and columns
    Row 2 = number with no decimals and columns
    Row 3 = percent with 4 decimals
    I can use a table cell renderer to set each COLUMN as one or the other formats like this:
    NumDispRenderer ndr = new NumDispRenderer();
    for(int i = 1;i<dates.size();i++) {
    table.getColumnModel().getColumn(i).setCellRenderer(ndr);
    Where NumDispRenderer is a class as follows:
    public class NumDispRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent (JTable table, Object value,boolean isSelected, boolean isFocused, int row, int column) {
    Component component = super.getTableCellRendererComponent (table,value,isSelected,isFocused,row,column);
    if (value != null && value instanceof Double) {
    DecimalFormat df = new DecimalFormat("###,###");
    String output = df.format(value);
    ((JLabel)component).setText(output);
    ((JLabel)component).setHorizontalAlignment(JLabel.RIGHT);
    } else {
    ((JLabel)component).setText(value == null ? "" : value.toString());
    return component;
    This is fine for the first two rows, but the third row (which is also an instance of Double) I would like to format differently.
    The tutorial and other postings have not given a solution to this problem. Any suggestions would be very appreciated.

    Hi,
    the method getTableCellRendererComponent() of your renderer gets the row as a parameter. So just create the label depending on that value. For 0<=row<=1 you create the label as is, and for row=2 you create another label with the Double formatted as you wish.
    Andre

  • JTABLE  Number Editor - Table Cell Renderer Clash

    Hello gentlemen,
    I have a JTABLE with an editable column 1. I implement a number editor and a table cell renderer (pls see below) to this column. I apply the setClickCountStart(2) method to the number editor in order to render each cell in the column editable only after two clicks. However, I believe setClickCountStart(2) is somehow overridden by a "default" functionality in my
    CustomTableCellRenderer.
    My problem is that any cell I select (click only once) in column1 is automatically editable whereas I only want a cell to be editable after two clicks.
    Please see my code below. Any comment is more than welcome!
    Cheers.
    hoodNumberEditor = new NumberEditor();
            hoodNumberEditor.setClickCountToStart(2);
            class CustomTableCellRenderer extends DefaultTableCellRenderer {
                public Component getTableCellRendererComponent(JTable table,
                        Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
                    Component cell = super.getTableCellRendererComponent(
                            table, obj, isSelected, hasFocus, row, column);
                    if (isSelected) {
                        cell.setBackground(Color.white);
                        cell.setForeground(Color.black);
                    return cell;
           CustomTableCellRenderer customrenderer = new CustomTableCellRenderer();
            table.getColumn(1).setCellRenderer(customrenderer);
            table.getColumn(1).setCellEditor(hoodNumberEditor);

    1) Your custom cell renderer does nothing extra, so you can depend on default renderer.
    2) Instead of extending JLabel and implementing TableCellReneder, you should extend DefaultTableCellRenderer and override its get renderer method because DefaultTableCellRenderer itself extends JLabel and aditionally it does some optimizations etc., which you can miss if you implement your own renderer.
    3) If you set foreground and background color in last else statement also, then you can see the values correctly in windows L&F as well.
    Thanks!

  • Customized table cell renderer doesn't work after table data model changed

    Hi:
    I have a jtable with a custimized table cell render (changes the row color). Everything works fine while the data model is unchanged. I can change the row color, etc. However, after I delete one row or any number of rows in the table, the data model is updated and the custmized table cell renderer is not being called anymore while jtable is rendering on its cells. Seems like the table cell render is no long associated with the jtable. Is this a known problem? Any help would be appreciated.
    Thanks

    I am having the same problem. Has anybody solved this issue?
    Thanks

  • Help: Jbo Exception non blocking when using table cell renderer?

    Hi,
    JClient 9.5.2.
    When using Table Cell Renderer on an table cell attribute that is defined mandatory and activating the insert button, the (oracle.jbo.AttrValException) JBO-27014 exception is caught but it is not blocking and a new row is still inserted.
    The JClient component demo, table attribute list, has the same behaviour.
    You can add multiple rows even if not all required attributes have been documented.
    Can a Swing specialist help me on this one?
    Example of Table Cell Renderer:
    public class TableBasicStatusRenderer extends DefaultTableCellRenderer
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
    int row, int column)
    JLabel lb = new JLabel((String) StaticData.getStatusName(value)); // retrieves label from Map
    return lb;
    Regards
    Frederic

    Hi,
    I found something interesting, it could be a WORKAROUND!
    I noticed that in another detail panel with table layout the JBO exception was blocking and adding another row before completing the row was NOT possible.
    In the create method of the entity object of the displayed View Object I iterate over the detail row iterator to retrieve a maximum value.
    By the end of the method the pointer is positionned after the last row.
    So I added to the detail panel that doesn't block following code:
    In create method of detail Entity Object Impl (only one entity object involved for this View)
    // Retrieve master EntityObjectImpl from association:
    PostalTariffImpl postalTariffImpl = getPostalTariffAssoc();
    // Retrieve detail default row iterator
    RowIterator ri = postalTariffImpl.getPostalDetailGroupAssoc();
    // Position pointer after last row
    ri.last();
    ri.next();
    Question: Why does this solve the problem?
    Regards
    Frederic
    PS Les mysteres de l'informatique!

  • Table cell renderer works with any L&F, but not with Windows

    Hi,
    I created a table cell renderer / editor for a combobox in a table cell. This works all as expected, but if the Look&Feel is com.sun.java.swing.plaf.windows.WindowsLookAndFeel, which is the system L&F on Vista, the selected values in the combobox are not shown in the cell after loosing focus. Metal LF and Motif LF work, and a third party one "TinyLF" works as well.
    Can anyone imagine why, and what needs to be changed to get a cross platform consistency without Metal LF?
    A compilable demo:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.io.IOException;
    import java.security.NoSuchAlgorithmException;
    import javax.swing.DefaultCellEditor;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    public class Test {
        static class CellRendererWithComboBox extends JLabel implements TableCellRenderer {
            JLabel label = new JLabel();
             * Set this renderer to the given column
             * @param column
             * @param r
             * @param editable
            public void setRendererTo(JTable table, int column, boolean editable) {
                TableColumn col = table.getColumnModel().getColumn(column);
                JComboBox xc = new JComboBox(new DefaultComboBoxModel(new Object[]{1, 2, 3, 4, 5, 6, 7}));
                col.setCellEditor(new ComboBoxEditor(xc));
                col.setCellRenderer(this);
                xc.setEditable(editable);
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                if (hasFocus && isSelected) {
                    if (isSelected) {
                        label.setForeground(table.getSelectionForeground());
                        label.setBackground(table.getSelectionBackground());
                    } else {
                        label.setForeground(table.getForeground());
                        label.setBackground(table.getBackground());
                    label.setText((value == null) ? "" : value.toString());
                    return label;
                } else {
                    label.setText((value == null) ? "" : value.toString());
                    return label;
            class ComboBoxEditor extends DefaultCellEditor {
                private final JComboBox box;
                private boolean fire = true;
                public ComboBoxEditor(JComboBox b) {
                    super(b);
                    this.box = b;
                    b.setLightWeightPopupEnabled(false);
                @Override
                public boolean stopCellEditing() {
                    if (fire) {
                        super.stopCellEditing();
                    return true;
                public void stopCellEditingSilent() {
                    fire = false;
                    stopCellEditing();
                    fire = true;
        public static void main(String... aArgs) throws NoSuchAlgorithmException, IOException {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException classNotFoundException) {
            } catch (InstantiationException instantiationException) {
            } catch (IllegalAccessException illegalAccessException) {
            } catch (UnsupportedLookAndFeelException unsupportedLookAndFeelException) {
            JFrame p = new JFrame();
            JTable t = new JTable();
            TableModel m = new DefaultTableModel(new Object[][]{
                        new Object[]{1, 2, 3, 4, 5, 6, 7},
                        new Object[]{1, 2, 3, 4, 5, 6, 7},
                        new Object[]{1, 2, 3, 4, 5, 6, 7},
                        new Object[]{1, 2, 3, 4, 5, 6, 7},
                        new Object[]{1, 2, 3, 4, 5, 6, 7}},
                    new Object[]{1, 2, 3, 4, 5, 6, 7});
            t.setModel(m);
            Test.CellRendererWithComboBox f = new CellRendererWithComboBox();
            f.setRendererTo(t, 1, true);
            p.setLayout(new BorderLayout());
            p.add(t, BorderLayout.CENTER);
            p.pack();
            p.setVisible(true);
    }

    1) Your custom cell renderer does nothing extra, so you can depend on default renderer.
    2) Instead of extending JLabel and implementing TableCellReneder, you should extend DefaultTableCellRenderer and override its get renderer method because DefaultTableCellRenderer itself extends JLabel and aditionally it does some optimizations etc., which you can miss if you implement your own renderer.
    3) If you set foreground and background color in last else statement also, then you can see the values correctly in windows L&F as well.
    Thanks!

  • How to set table cell renderer in a specific cell?

    how to set table cell renderer in a specific cell?
    i want set a cell to be a button in renderer!
    how to do?
    any link or document can read>?
    thx!

    Take a look at :
    http://www2.gol.com/users/tame/swing/examples/SwingExamples.html
    It is very interesting, and I think your answer is here.
    Denis

  • Custom Table Cell Renderer Unable To Set Horizontal Alignment

    Hello,
    I have a problem that I'm at my wit's end with, and I was hoping for some help.
    I need to render the cells in my table differently (alignment, colors, etc) depending on the row AND the column, not just the column. I've got this working just fine, except for changing the cell's horizontal alignment won't work.
    I have a CustomCellRenderer that extends DefaultTableCellRenderer and overrides the getTableCellRendererComponent() method, setting the foreground/background colors and horizontal alignment of the cell based on the cell's value.
    I have a CustomTable that extends JTable and overrides the getCellRenderer(int row, int column) method to return a private instance of this CustomCellRenderer.
    This works fine for foreground/background colors, but my calls to setHorizontalAlignment() in the getTableCellRendererComponent() seem to have no effect, every cell is always displayed LEFT aligned! It's almost like the cell's alignment is determined by something else than the table.getCellRenderer(row,column).getTableCellRendererComponent() method.
    I've also tried setting the renderer for every existing TableColumn in the TableModel to this custom renderer, as well as overriding the table's getDefaultColumn() method to return this custom renderer as well for any Class parameter, with no success.
    No matter what I've tried, I can customize the cell however I want, EXCEPT for the horizontal alignment!!!
    Any ideas???
    Here's the core custom classes that I'm using:
    class CustomTable extends JTable {
    private CustomRenderer customRenderer = new CustomRenderer();
    public CustomTable() {
    super();
    public TableCellRenderer getCellRenderer(int row, int column) {
    return customRenderer;
    } // end class CustomTable
    class CustomRenderer extends DefaultTableCellRenderer {
    public CustomRenderer() {
    super();
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if (row % 2 == 0) {
    setForeground(Color.red);
    setHorizontalAlignment(RIGHT);
    } else {
    setForeground(Color.blue);
    setHorizontalAlignment(LEFT);
    return this;
    } // end class CustomRenderer
    Even worse, I've gotten this to work fine in a trivial example I made to try and re-create the problem. But for some reason, this same thing is just not working for horizontal alignment in my actual project?!?
    Anyone have any ideas how the cell's horizontal alignment set in the getTableCellRendererComponent() method is being ignored or overwritten before the cell is being displayed???
    Thanks, any help is appreciated,
    -Alex Blume

    Ok, so I've looked into their source and I think I know where and what the trouble is. The JTable.java has a method called:
    3658> public TableCellRenderer getCellRenderer(int row, int column) {
    3659> TableColumn tableColumn = getColumnModel().getColumn(column);
    3660> TableCellRenderer renderer = tableColumn.getCellRenderer();
    3661> if (renderer == null) {
    3662> renderer = getDefaultRenderer(getColumnClass(column));
    3663> }
    3664> return renderer;
    3665> }
    starting at line 3658 of their source code. It retrieves the TableCellRenderer on line 3660 by calling the tableColumn's getCellRenderer method. This is found in the TableColumn.java class:
    421> public TableCellRenderer getCellRenderer() {
    422> return cellRenderer;
    423> }
    See the problem? Only ONE cell Renderer. It's referring to a variable found at line 140 which is of type TableCellRenderer ... well actually it's created as a DefaultTableCellRenderer at some point since TableCellRenderer is an interface.
    Basically the fix is this:
    In the TableColumn.java file, a collection (Vector, LinkedList, whatever) needs to keep track of each cell's renderer. This will solve the solution. Of course this will be something that you or I can make.
    What's funny is the contradiction in documentation between JTable's and TableColumn's getCellRenderer() method. First, if we look at TableColumn's documentation it states:
    "Returns the TableCellRenderer used by the JTable to draw values for this column."
    Based on that first statement, the getCellRenderer() method in TableColumn is doing its job exactly. No lies, no contradictions in what it does.
    However, that method is called up inside of the JTable's getCellRenderer() method which says a completely different thing which is:
    "Returns an appropriate renderer for the cell specified by this row and column."
    Now we have a problem. For the cell specified. It appears that the rush to push this out blinded some developer who either:
    1) mis-interpreted what the JTable getCellRenderer() method was supposed to do and inadvertently added a feature or;
    2) was in a 2 a.m. blitz, wired on Pepsi and adrenalin and wrote the bug in.
    Either way, I'm really hoping that they'll fix this because it will take care of at least 2 bugs. Btw, anyone interested in posting a subclass to solve this problem (subclass of TableColumn) is more than welcome. I've spent much too much time on this and my project is already behind so I can't really afford any more time on this.
    later,
    a.

  • JComboBox table cell renderer problem

    The following program demonstrates a difference in behavior of table cell editor combobox based on whether the combo box is editable or not. If the ComboBox is editable, then the first click into the table cell starts the edit and shows the popup, whereas if the combobox is not editable then it takes 2 clicks into the cell to cause the popup to become visible. I am trying to achieve the 1 click popup behavior while keeping the combobox not editable. Run the following program, and click on various cells, the top table requires 2 clicks for a popup, and the bottom table only 1. The only difference is the editablility of the combobox. (This is windows l&f)
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class JTableComboBoxCellEditorTest {
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){e.printStackTrace();}
              DefaultTableModel tableModel = new DefaultTableModel(
                        new Object[][] {{"1","2"},{"2","3"},{"3","1"} },
                        new Object[]{"Column1","Column2"}
              final JComboBox renderer = new JComboBox(new Object[]{"1","2","3"});
              TableCellRenderer cellRenderer = new TableCellRenderer() {
                   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col){
                        renderer.setSelectedItem(value);
                        return renderer;
              JTable table1 = new JTable(tableModel);
              final JComboBox badEditor = new JComboBox(new Object[]{"1","2","3"});
              badEditor.setEditable(false);
              table1.setDefaultEditor(Object.class, new DefaultCellEditor(badEditor));
              table1.setDefaultRenderer(Object.class, cellRenderer);
              table1.setRowHeight(24);
              JTable table2 = new JTable(tableModel);
              final JComboBox goodEditor = new JComboBox(new Object[]{"1","2","3"});
              goodEditor.setEditable(true);
              table2.setDefaultEditor(Object.class, new DefaultCellEditor(goodEditor));
              table2.setRowHeight(24);
              table2.setDefaultRenderer(Object.class, cellRenderer);
              JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT,new JScrollPane(table1), new JScrollPane(table2));
            JFrame f = new JFrame("Table Test");
            f.getContentPane().add(split,BorderLayout.CENTER);
                f.setBounds(100,100,500,500);
            f.addWindowListener(new WindowAdapter() {
                 public void windowClosing(WindowEvent e) {
                      System.exit(0);
            f.setVisible(true);
    }

    Setting a renderer for first column:
    assetTable.getColumnModel().getColumn(1).setRenderer(tableRenderer);Your custom renderer must honor the selection color and border or otherwise the first column will not look selected. You should subclass DefaultTableCellRenderer:
    public class AssesTableRenderer extends DefaultTableCellRenderer  {
      public Component getTableCellRendererComponent(...) {
        // default renderer uses a label
        JLabel label = (JLabel)super.getTableCellRendererComponent(...);
        // decide icon to use
        Icon icon = ...;
        label.setIcon(icon);
       return label;
    }

  • Table Cell Renderer Problem

    I've created a JTable and filled it with data. I created my own header renderer so that I could have more control over the font of the header. I did the same with the cells of the table. Before I created the cell renderer, the cell and row selection (the highlighting of the selections) worked fine. Once I created and implemented the cell renderer, I can set the font the way I want, but the cell no longer highlights the selected rows. It's selecting the rows (my System.out.println in getTableCellRendererComponent() comes back with data). I'm not sure what I'm doing wrong. Here's some of the code....
    runTable = new JTable(tableModel);
    runTable.setBackground(Color.white);
    runTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    CellRenderer cellRenderer = new CellRenderer();
    // Set column 1's header
    String[] header1 = {"Time"," Of ","Day"};
    TableColumn col1 = runTable.getColumnModel().getColumn(0);
    col1.setHeaderValue(header1);
    col1.setCellRenderer(cellRenderer);
    String[][] parms = zoomplot.zmenubar.getParmSel();
    TableColumn col;
    for (int i = 0; i < parms.length; i++) {
    String[] header = new String[3];
    header[0] = parms[0];
    header[1] = " (" + parms[i][1] + ") ";
    header[2] = "Rate " + parms[i][2];
    col= runTable.getColumnModel().getColumn(i + 1);
    col.setHeaderValue(header);
    // col.setMaxWidth(100);
    col.setCellRenderer(cellRenderer);
    class CellRenderer extends JLabel
    implements TableCellRenderer {
    Color background = null;
    public CellRenderer() {
    // setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    // setOpaque(false);
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus,
         int row, int col) {
    removeAll();
    invalidate();
    add(Box.createVerticalGlue());
    setText((String)value);
    setFont(Utils.courierBold11);
    setHorizontalAlignment(SwingConstants.CENTER);
    setAlignmentX((float)0.5);
    if (isSelected) {
    this.setBackground(Color.black);
    // System.out.println("Row " + row + ", Col " + col + " is selected");
    return this;
    public void setBackground(Color back) {
    background = back;
    super.setBackground(back);
    I even tried to "manually" set the highlighting in getTableCellRendererComponent() ...
    if (isSelected) {
    this.setBackground(Color.black);
    but that didn't work either. Any Ideas..... Thanks.....

    When creating a custom renderer it is generally easier to extend the DefaultTableCellRenderer as it already has the custom code to do row highlighting, border selection etc. Also it has been optimized to paint faster.
    In your particular case it looks like your don't even need to do that. Just create a DefaultTableCellRenderer and change a few of its properties. Something like:
    // Override default renderer for a specific column
    DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
    centerRenderer.setHorizontalAlignment( JLabel.CENTER );
    centerRenderer.setFont(...);
    table.getColumnModel().getColumn(2).setCellRenderer( centerRenderer );

  • Table Cell Renderer Customization not working

    I have a customized cell renderer that works wonderfully, it paints the background and text like it should, but I am also trying to paint a stripe like a 1 sided border across the top of the table cell, but (and this is the wierd part) only the first table column header is painting with this "stripe" on the top of it, every other column header and every other table cell do not paint with stripe on it. I print out the coords as I pass them to the graphics object to paint the line and the coords are correct, but the lines only show up in the first cell.
    I have tried to put this code into the Renderer, and today I tried to put it into the UIComponent with the same result.
    Relevant code:
    // inner class for the renderer
    private class LabelUI extends MetalLabelUI
    public void paint(Graphics g,JComponent c)
    // PAINT THE LABEL(RENDERER) USING THE NORMAL ROUTINE
    super.paint(g,c);
    // PICK A COLOR TO TEST THE CODE
    g.setColor(Color.green);
    // DUMP THE COORDS OUT TO CONSOLE
    System.out.println("Drawing a line from :"+
    c.getX()+","+(c.getY()+1)+","+
    (c.getX()+c.getWidth())+","+(c.getY()+1));
    // DRAW THE LINES
    g.drawLine(c.getX(),c.getY()+1,c.getX()+c.getWidth(),c.getY()+1);
    g.drawLine(c.getX(),c.getY()+2,c.getX()+c.getWidth(),c.getY()+2);
    }

    camickr- thanks for the input. I had tried a matte border yesterday in the renderer and the L&F object and couldn't get it to paint, but maybe I have something set elsewhere that is preventing it from painting, so I'll give that one another try. If I come up with an answer I'll be sure to post! -dohare
    If I understand the question then take a look at the
    HighlightCellRenderer class of this little
    application. It uses vertical lines on certain
    columns:
    http://www.discoverteenergy.com/files/RHex.zip
    run the program: java Hex

  • Custom table cell renderer in a JTable is not called

    Hello, all,
    I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.
    My code snippents are as follows:
    //Declare the table and add custom cell renderer
    JTable table = new JTable (7,7);
    table.setCellSelectionEnabled (true);
    table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    //Add the custom cell renderer to render objects of type Item
    table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());
    //Get the selected cells and change the object type in those cells
    //This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
    int rowIndexStart = table.getSelectedRow();
    int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
    int colIndex = table.getSelectedColumn();
    Item item = new Item ();
    for (int i = rowIndexStart; i<=rowIndexEnd; i++){
                  table.setValueAt(item, i, colIndex);
                 //I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called.  Instead, the item.toString() value is displayed in the cell.   What is wrong?
    //Definition of custom cell renderer. 
    //the getTableCellRendererComponent is never called, since the System.out.println never prints.  I expected this method to be called as soon as the Item object is added to the cell.  Am I wrong in expecting that?
    class CustomTableCellRenderer extends DefaultTableCellRenderer  {
        public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
            System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
            if (this.isFocusOwner()) {
            cell.setBackground( Color.red );
            cell.setForeground( Color.white );
            return cell;
    } Please, help,
    Thank you!
    Elana

    The suggestion given above assumes that all the data in a given column is of the same type.
    If you have different types of data in different rows the you should be overriding the getCellRenderer(...) method. Something like:
    public TableCellRenderer getCellRenderer(int row, int column)
        Object o = getValueAt(row, column);
        if (o instanceof Item)
            return yourCustomRenderer
        else
            return super.getCellRenderer(row, column);
    }

  • Slide show in table cell and text in layer above images

    I need to create a slide show within
    a table cell (one cell of several).  The
    display should commence after the launch page has been completely loaded and only appear once.  Also, there needs to be text in a layer above the slide images which changes coordinated with each slide but is generated independent of each slide and therefore may be positioned within the cell independently.
    Anyone?

    Hi again Nancy,
    You've provided very helpful information in the past.  The code for the "show" in the upper right position would be perfect if the text-bar background could be made transparent and positioned higher against the image. Your suggestion has forced me to clarify my concept in my own mind.  The need for transparency hadn't occurred to me yet. 
    An alternative would be the upper left "show" in a bottom layer with text with a transparent background in a top layer.  The text in the top layer would remain constant from the time of the page's loading; i.e., would be independent of changes in the bottom layer.  Perhaps I could figure out the code necessary to coordinate that text's change of shade from one slide to the next appropriate to the slide's shade.
    I'm assuming that a table cell can be partitioned into layers using HTML and each layer programmed independently using JavaScript.
    Thanks again for your prompt attention.

  • Table Cell Rendering dynamically

    Hi All,
    We have a requirement to develop an application which should populate table view dynamically with editable UI elements for the selected record and the other records should in viewable. Could you please guide me how to do the tale cell rendering in a table dynamically. I have used the below code but it is not working for me, please provide any suggestions to do any changes for the below code
    IWDTableStandardCell sCell = (IWDTableStandardCell) view.createElement(IWDTableStandardCell.class, null);
    sCell.setVariantKey("key");     
    IWDInputField inputeditor =(IWDInputField) view.createElement(
                             IWDInputField.class,null);
    inputeditor.bindValue(attrInfo);                         
    sCell.setEditor(inputeditor);
    column.setSelectedCellVariant(IPrivateABCView.IUserTabDataElement.KEY);
    column.addCellVariant(sCell);
    Regards
    Suresh

    Hi,
    Yeh you are correct, NULLs are also accepting. Could you please provide any solution for my requirement?
    Regards
    Suresh

  • Problem with CheckBox as table cell renderer

    i m making a JTable having three columns.
    i m also making a cellRenderer of my own MyRenderer
    extending Jcheckbox and implementing TableCellRenderer
    now i m setting MyRenderer as renderer for third column in my table and
    DefaultCellEditor with jcheckbox as parameter as cell editor for this column
    the code is like this--------------------
    ****making of JTable****
    table= new JTable(3,3);
    JScrollPane scrollPane = new JScrollPane(table);
    TableColumn tableColumn = table.getColumn("Male"); // let us suppose that this gives third column
    tableColumn.setCellRenderer(new MyRenderer ());
    tableColumn.setCellEditor(new DefaultCellEditor(new JCheckBox()));
    *****The classs implementing TableCellRenderer is given below******
    class MyRenderer extends JCheckBox implements TableCellRenderer{
    public MyRenderer(){
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column){
    if(value != null){
    Boolean booleanValue = (Boolean)value;
    setSelected(booleanValue.booleanValue());
    return this;
    ***********************************Problem****************************
    The problem is that when we click on the cell of that column first time,
    all the cells are selected.
    I don't want to use getColumnClass() method for this problem .
    If possible , please give some other solution.
    what is the problem behind this,If anybody can help us.
    Thanks in advance.

    I think the problem is, when the value is null the checkbox return with the selected state, b'coz u r
    returning the checkbox (as it is). so pl'z try with below code (ADDED).
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column){
    if(value != null){
    Boolean booleanValue = (Boolean)value;
    setSelected(booleanValue.booleanValue());
    else /// ADDED
    setSelected(false);/// ADDED
    return this;
    Nediaph.

Maybe you are looking for