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

Similar Messages

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

  • 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

  • Is anyone else having table border rendering problems in Firefox 3.6.7 for Mac?

    I recently applied a Mac Firefox update (not sure which one, but I'm currently on 3.6.7) that introduced some strange table border rendering behaviors. Long story short, on certain pages that I visit regularly, the right-most table borders are now rendering erratically. The problem does not occur in Safari or Chrome on Mac, nor does it occur in IE or Firefox on Windows. Seems specific to Mac Firefox.
    To reproduce, using Firefox 3.6.7 on Mac, browse to the following URL:
    http://www.relativityreport.com/?page_id=963
    ...and note the erratic rendering of the right-most table cells on the page (you may need to scroll down to the bottom-most table to see the problem...but not always). They should be gray, but often appear blank (not necessarily all at once). Refresh the page a few times and note how the missing borders randomly appear and disappear. Now click your browser's back button. When the previous page has loaded, click the forward button to return to the affected URL. Note now how all cells render correctly.
    Thanks!

    I am also getting a similar error. When I increase the border width to 2px or more it becomes sort of eroded.I am using windows 7 firefox 4. Borders seem fine in all other major browsers including IE9.
    [http://year3.masterspokerleague.com/index.php?option=com_poker&view=overall&season_id=2 Example] http://year3.masterspokerleague.com/index.php?option=com_poker&view=overall&season_id=2
    Any ideas?

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

  • Cell Renderer Problem

    Hello. I have a problem with my cell rendering. I am trying to make font in a certain row appear red. My code works well but when you try filtering using row sorter or using the table header's, the colored rows do not change. How can I make the the renderer maybe check for values on every sort?
    Here is a sample of sorting using the table header.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class table extends JFrame {
         public static void main(String[] args) {
              new table();
         public table() {
              initComponents();
              table1.setAutoCreateRowSorter(true);
              for (int i = 0; i<table1.getColumnCount(); i++) {
                   TableColumn column = table1.getColumnModel().getColumn(i);
                   column.setCellRenderer(new myTable());
                   if (i == 0||i==7||i==8){
                        column.setPreferredWidth(100);
                   else if(i==3||i==4){
                        column.setPreferredWidth(180);
                   else if (i==5||i==6){
                        column.setPreferredWidth(120);
                   else if (i==9){
                        column.setPreferredWidth(60);
                   else {
                        column.setPreferredWidth(130);
         public class myTable extends DefaultTableCellRenderer{
              @Override
              public Component getTableCellRendererComponent(JTable table, Object value,
                        boolean isSelected,boolean hasFocus, int row, int col){
                   Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                   String qtyValue =  table.getModel().getValueAt(row, 1).toString();
                   if(Integer.valueOf(qtyValue)<3){
                        comp.setForeground(Color.red);
                   else{
                        comp.setForeground(Color.black);
                   return comp;
         private void initComponents() {
              // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
              scrollPane1 = new JScrollPane();
              table1 = new JTable();
              //======== this ========
              Container contentPane = getContentPane();
              contentPane.setLayout(null);
              //======== scrollPane1 ========
                   //---- table1 ----
                   table1.setModel(new DefaultTableModel(
                        new Object[][] {
                             {"Item A", "1"},
                             {"Item B", "2"},
                             {"Item C", "1"},
                             {"Item D", "4"},
                             {"Item E", "5"},
                             {"Item F", "2"},
                             {"Item G", "3"},
                             {"Item H", "7"},
                             {"Item I", "2"},
                             {"Item J", "9"},
                        new String[] {
                             null, null
                   scrollPane1.setViewportView(table1);
              contentPane.add(scrollPane1);
              scrollPane1.setBounds(5, 0, 465, 320);
              { // compute preferred size
                   Dimension preferredSize = new Dimension();
                   for(int i = 0; i < contentPane.getComponentCount(); i++) {
                        Rectangle bounds = contentPane.getComponent(i).getBounds();
                        preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                        preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                   Insets insets = contentPane.getInsets();
                   preferredSize.width += insets.right;
                   preferredSize.height += insets.bottom;
                   contentPane.setMinimumSize(preferredSize);
                   contentPane.setPreferredSize(preferredSize);
              pack();
              setLocationRelativeTo(getOwner());
              this.setVisible(true);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              // JFormDesigner - End of component initialization  //GEN-END:initComponents
         // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
         private JScrollPane scrollPane1;
         private JTable table1;
         // JFormDesigner - End of variables declaration  //GEN-END:variables
    }

    1. By convention, class names in Java start with an uppercase letter. I would say Table, not table, except that Table is a confusing name for a class.
    2. Swing GUIs should always be constructed and manipulated on the EDT.
    To answer your question
    when you try filtering using row sorter or using the table header's, the colored rows do not change. How can I make the the renderer maybe check for values on every sort?Use the methods of JTable that convert between the view and model index.
    db

  • JTabbedPane Cell Renderer problem

    Hi
    I have a JTabbedPane with two tabs both of which contain JTables with custom cell renderers. When i tab beteewn these tables the rendering gets "messed up". If I click on the table or alt tab between the application window and another window the table seems to right itself. I Have tried to call a repaint when switching tabs but this does not ssem to help... Can anyone help me please?

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables
    If your code works on a normal table, it should make no difference that you have two different tables on two different tabs. So the problem is with you code and we have no idea what your code looks like.

  • MultLine Cell Renderer problem

    I have a Custom Cell Renderer which is a scrollPane with a JTextArea. My problem is that the Cell does not scroll when I click the arrows on the vertical scroll Bar.
    Does Anyone Have Any suggestions?
    Here is the code:
    public class ScrollCellRend implements TableCellRenderer {
    private JTextArea ta;
    private JScrollPane scrollPane;
    public ScrollCellRend() {
    ta = new JTextArea();
    scrollPane = new JScrollPane(ta);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);
    ta.setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    ta.setForeground(table.getSelectionForeground());
    ta.setBackground(table.getSelectionBackground());
    } else {
    ta.setForeground(table.getForeground());
    ta.setBackground(table.getBackground());
    ta.setFont(table.getFont());
    if (hasFocus) {
    if (isSelected)
    ta.setBorder(BorderFactory.createLineBorder(Color.blue));
    if (table.isCellEditable(row, column)) {
    ta.setForeground(UIManager.getColor("Table.focusCellForeground"));
    ta.setBackground(UIManager.getColor("Table.focusCellBackground"));
    } else {
    ta.setBorder(new EmptyBorder(1, 2, 1, 2));
    ta.setText((value == null) ? "" : value.toString());
    return scrollPane;

    Hi dave,
    Your must implement a custom TableCellEditor. I'm giving a small demo that can explain how you can achive this thing (3 classes) ---
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class MainFrame extends JFrame {
    private boolean DEBUG = true;
    public MainFrame() {
    super("MainFrame");
    Object[][] data = {    {"Mary"} };
    String[] columnNames = {"First Name"};
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setDefaultRenderer(String.class,new ScrollCellRend());
    TableColumnModel columnModel = table.getColumnModel();
    TableColumn column = columnModel.getColumn(0);
    column.setCellEditor(new LocationTableCellEditor("First Name"));
    column.setPreferredWidth(150);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public static void main(String[] args) {
    MainFrame frame = new MainFrame();
    frame.pack();
    frame.setVisible(true);
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import javax.swing.border.*;
    public class ScrollCellRend implements TableCellRenderer {
    private JTextArea ta;
    private JScrollPane scrollPane;
    public ScrollCellRend() {
    ta = new JTextArea();
    scrollPane = new JScrollPane(ta);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    ta.setLineWrap(true);
    ta.setWrapStyleWord(true);
    ta.setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    ta.setForeground(table.getSelectionForeground());
    ta.setBackground(table.getSelectionBackground());
    } else {
    ta.setForeground(table.getForeground());
    ta.setBackground(table.getBackground());
    ta.setFont(table.getFont());
    if (hasFocus) {
    if (isSelected)
    ta.setBorder(BorderFactory.createLineBorder(Color.blue));
    if (table.isCellEditable(row, column)) {
    ta.setForeground(UIManager.getColor("Table.focusCellForeground"));
    ta.setBackground(UIManager.getColor("Table.focusCellBackground"));
    } else {
    ta.setBorder(new EmptyBorder(1, 2, 1, 2));
    ta.setText((value == null) ? "" : value.toString());
    return scrollPane;
    import java.awt.*;
    import java.util.EventObject;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class LocationTableCellEditor implements TableCellRenderer, TableCellEditor {
    private JPanel panel = new JPanel(new GridLayout(1,1,2,1));
    private EventListenerList listenerList = new EventListenerList();
    private ChangeEvent event = new ChangeEvent(this);
         private JTextArea ta;
         private JScrollPane scrollPane;
    public LocationTableCellEditor(String type) {
              ta = new JTextArea();
              scrollPane = new JScrollPane(ta);
              scrollPane.setBorder(BorderFactory.createEmptyBorder());
              ta.setLineWrap(true);
              ta.setWrapStyleWord(true);
              ta.setOpaque(true);
    panel.add(scrollPane);
    panel.setPreferredSize(new Dimension(80,15));
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,int row, int column) {
    String s = (String)value;
    ta.setText(s);
    return panel;
    public Component getTableCellEditorComponent(JTable table,
    Object value, boolean isSelected, int row, int column) {
    return getTableCellRendererComponent(table, value,isSelected, true, row, column);
    public boolean isCellEditable(EventObject anEvent) {
    return true;
    public boolean shouldSelectCell(EventObject anEvent) {
    return true;
    public void cancelCellEditing() {
    public boolean stopCellEditing() {
    fireEditingStopped();
    return true;
    public Object getCellEditorValue() {
    return ta.getText();
    public void addCellEditorListener(CellEditorListener l){
    listenerList.add(CellEditorListener.class, l);
    public void removeCellEditorListener(CellEditorListener l) {
    listenerList.remove(CellEditorListener.class, l);
    protected void fireEditingStopped(){
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingStopped(event);
    protected void fireEditingCanceled() {
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2)
    ((CellEditorListener)listeners[i+1]).editingCanceled(event);
    void p(String s) {System.out.println(s);}
    Hope it will help you.
    -Pratap

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

  • 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

Maybe you are looking for

  • MBP 1.83 CoreDuo - will SATA300 drives work in my SATA-150 laptop?

    I've had this book for 4 years and its time to bump up the drive space from the stock Fuji 80GB. System Profiler indicates an SATA interface, which gives me a maximum 1.5Gb transfer rate. I did a search for compatible drives and the list is pretty sl

  • Part 2 : can i create an instance of ArrayList ?

    Hey thanks so much for the reply. Let me tell you the exact scenario. I'm actually developing a struts-application. Hope I can get some help here too. I have: 1. login.jsp-where user logs in. -I have a userid and a password as default values for each

  • Changing Sequence Settings for HD

    Hi Gang Working with FC6 I work mostly with Standard Def, but I have a few pieces/clips of HD. If I change the Sequence Settings here, as prompted, will ALL the sequence settings also be changed to exisiting Projects which contain mostly Standard Def

  • Can I use Event structures in a subVI?

    Hi, I have a subVI (ProvaEv1.vi) that use an event structure inside. But when I use it in a VI (ProvaVI.vi) the event structure in the subVI doesn't catch the events. I tried to insert the event structure in a while loop but it doesn't work too. Coul

  • Pie chart  display error

    Hi I created pie chart using CFCHART tag. In the chart display, data values overlap on one another in the display. How to rectify this error. Kindly help me in this regard. Advance thanks