Jtable background????

I wirte Jtable and then using sort and filter to this table. sort and filter are working fine but the backgound color for each column is not changed.
the code like this
package test;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import timelineveiwer.TableColor;
public class test {
public static void main(String args[]) {
JFrame frame = new JFrame("Regexing JTable");
TableColor tableColor = new TableColor();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object rows[][] = { { "File", "About", 44.36 }, { "Internet", "Boy", 44.84 }, { "File", "Cat", 463.63 },
{ "D", "Day", 27.14 }, { "File", "Eat", 44.57 }, { "F", "Fail", 23.15 },
{ "File", "Good", 4.40 }, { "H", "Hot", 24.96 }, { "File", "Ivey", 5.45 },
{ "J", "Jack", 49.54 }, { "File", "Kids", 280.00 } };
String columns[] = { "Symbol", "Name", "Price" };
TableModel model = new DefaultTableModel(rows, columns) {
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
return returnValue;
final JTable table = new JTable(model);
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
((DefaultTableModel)model).fireTableDataChanged();
table.setRowSorter(sorter);
JScrollPane pane = new JScrollPane(table);
frame.add(pane, BorderLayout.CENTER);
     for(int i = 0;i<3;i++){
          TableColumn tcol = table.getColumnModel().getColumn(i);
     tcol.setCellRenderer(tableColor);
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel("Filter");
panel.add(label, BorderLayout.WEST);
final JTextField filterText = new JTextField("A");
panel.add(filterText, BorderLayout.CENTER);
frame.add(panel, BorderLayout.NORTH);
JButton button = new JButton("Filter");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
     TableColor tableColor1 = new TableColor();
String text = filterText.getText();
if (text.length() == 0) {
sorter.setRowFilter(null);
} else {
sorter.setRowFilter(RowFilter.regexFilter(text));
frame.add(button, BorderLayout.SOUTH);
frame.setSize(300, 250);
frame.setVisible(true);
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
public class TableColor extends DefaultTableCellRenderer{
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 s = table.getModel().getValueAt(row, 0).toString();
          if(s.equalsIgnoreCase("Internet"))
          comp.setBackground(Color.pink);
          else if(s.equalsIgnoreCase("File"))
          comp.setBackground(Color.yellow);
          else {
               comp.setBackground(Color.green);
          return( comp );
please help me..thanks....

If you look at the source code for DefaultTableCellRenderer.getTableCellRendererComponent then you will see how the cell colours are selected based on focus/selection/editability.
Then you can write your own TableCellRenderer to take control of these things.

Similar Messages

  • JTable background color

    How can I change a JTable's background color?

    Hi,
    I guess, you want to change the background of the cells, don't you?
    There are 2 methods, where you can change the components, that are used for rendering and editing of a cell - prepareRenderer(...) and prepareEditor(...)-method - overwrite them in your JTable subclass as follows:
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
    Component c = super.prepareRenderer(renderer,row,column);
    // now set the background color - here red for example
    c.setBackground(Color.red);
    return c;
    } // end of method
    // now we do the same with prepareEditor
    public Component prepareEditor(TableCellEditor editor,  int row, int column) {
    Component c = super.prepareEditor(editor,row,column);
    c.setBackground(Color.red);
    return c;
    }// end of methodHope that helps
    greetings Marsian

  • Setting JTable Background Row Color based on cell Value

    I am new to Java and JDeveloper (so bear with me). I have managed to create a Swing form using BC4J (Jdev 10g preview) which contains a scrollpane with a view object represented as a table. I would like to be able to color the rows that are displayed within the table differently depending on the value of a cell/column within the row. Its not obvious to me from the property inspector how to do this - I assume it is possible as all the other bells and whistles appear to be in place.
    Thanks in advance
    Simon

    Simon,
    in Swing this is not done through properties but a custom cell renderer. You can check the Swing tutorial on http://java.sun.com for how to modify the default behavior of a JTable component. A very good book to learn Swing is "Java Swing" from O'Reilly (ISBN 0-596-00408-7).
    ADF JClient uses Swing components and therefore everything you can do in Swing you can do with JClient.
    Frank

  • 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 do I set background color of cell using JTable?

    Hello all!
    I have a question on the use of JTables. I am using a JDialog consisting of a JTable and a number of buttons to insert and to select OK or cancel. Everything is working perfectly, but I now must add editing capabilities to prevent invalid data being used in a SQL query to update or insert rows.
    So far I can't figure out how to get at a cell to set the background to red if the user inputs a Date incorrectly. Upon setValueAt(), I take this value and check for standard format errors. I hope to someday convert the column altogether to a Data object (or some form since Date is deprecated):-) For the time being, I know when an error occurs, but don't have the foggiest idea how to render the error (set backround to red).
    I need to give you more info too, since the way we do things is to make it as complicated as possible for job security and to impress the newbies(or scare them back to COBOL). When I setValueAt(), I have a DefaultDataElement object that houses everything for a given column in DB2. It has column name, length, data type, is it new, original value, current value, etc. If one doesn't exist, then I create one. After all said and done, I parse thru these elements and build my update/insert query and then execute the query.
    The event starts as soon as the user presses the OK button. But, if a date cell contains an invalid date, I need to halt processing (which I've done) and somehow let the user know which cell was invalid. We consider our users dumb (they really aren't, but the assumption is made), so I can't just say "error occurred in table. Verify data and try again". That won't work:-) Gotta be able to show them what cell is bad.
    Any ideas?
    Thanks,
    Patrick

    I finally figured it out. I was always close, but it wasn't until late yesterday that the light bulb came on. I was setting the background on the component in getTableCellEditorComponent() by grabbing the super.getTableCellEditorComponent(). The problem was all this was located in an editor, not renderer. So what happened was as I edited the cell the check would be performed then, not as focus was lost. When focus was lost, the red background went back to normal.
    I ripped the code out and made a custom renderer and got closer. Problem was the whole column had a red background. Even specifying the row and column in getTableCellRendererComponent didn't apply just to that cell. That row and column is only for obtaining the data in the cell, but anything affecting the component will affect the column, since I added the renderer to my TableColumn:-) I need to add error logic to my model and when an error occurs, set a boolean flag in a 2 dimensional array where the row and column is used to get to it from the renderer.
    Thanks for the help!!!

  • How to change the Background color of a cell in JTable

    hi!
    Actually i want to change the background color of few cells in JTable
    is there any method to make this change in JTable ?
    and also is it possible to have 5 rows with single column and 5 rows with 3 columns in a single JTable

    i want to change the background color of few cells in JTableDepending on your requirements for the coloring of cells it may be easier to override the prepareRenderer() method of JTable:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • Change the background color of a cell in JTable

    Hi all,
    How can I change the background color of individual cell in JTable. I need to construct my own TableCellRenderer or not? I'm now using the DefaultTableCellRenderer now.
    Thx

    You could create your own renderer or you could try something like:
    table = new JTable(model)
         public TableCellRenderer getCellRenderer(int row, int column)
              DefaultTableCellRenderer tcr =
               (DefaultTableCellRenderer)super.getCellRenderer(row, column);
              if (row == 1 && column == 1)
                   tcr.setBackground(Color.green);
              else
                   tcr.setBackground(Color.red);
              return tcr;
    };

  • How to set background color of row in JTable

    Hi,I want to set different background color to rows in JTable according to some value in the this row.
    eg.
    no name isGood
    1 aaa yes (this row's background color is red)
    2 bbb no (this row's background color is blue)
    3 ccc yes (this row's background color is red)
    4 ddd yes (this row's background color is red)
    5 eee no (this row's background color is blue)
    thanks

    thanks!*_*                                                                                                                                                                                                                                                       

  • How to set background color in row of JTable ?

    i am new in java please tell me about How to set background color in row of JTable ? please example code. Thnak you.

    Here is an example: http://www.javaworld.com/javaworld/javaqa/2001-09/03-qa-0928-jtable.html
    For more info on how to use tables read the swing tutorial: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    ICE

  • Help! coloring background one row for 3 seconds in JTable with SwingTimer

    Hi, I am struggling with this for the past three days but cannot come up with a solution.
    I have a JTable and when i insert a new Row, i want to give that row a backgroundcolor for 3 seconds/ or let it blink for 3 seconds and then let it return to its original background color. While the current row is yellow, i want to insert a new row which also would be yellow for 3 seconds. The previous row would return white earlier than the row after, because that row is inserted earlier.
    the problem is, that when i add a new row while the current row is yellow, the new row has the timer of the previous row, which means that the last row inserted will stay yellow for a shirter time, which i do not want.
    i want a 3 second bgcolor for everyrow inserted. how can i achieve this ?
    My code:
    startBlinking() is called when a new row is being added to the JTable
    public void startBlinking() throws InterruptedException{
    if (timer.isRunning()){
    timer.setInitialDelay(2);
    timer.start();
    ----------------------- in another class:
    //attributes
    Action updateCursorAction = getAction();
    Timer timer = new Timer(3000, updateCursorAction);
    public Action getAction(){
    updateCursorAction = new AbstractAction() {
    boolean shouldDraw = false;
    public void actionPerformed(ActionEvent e) {
    if (shouldDraw =! shouldDraw) {
    blinkingYellow();
    } else{
    blinkingWhite();
    timer.stop();
    return updateCursorAction;
    public void blinkingWhite(){
    receiverdata_Table.setRowSelectionInterval(0, 0);
    receiverdata_Table.setSelectionBackground(Color.white);
    public void blinkingYellow(){
    receiverdata_Table.setRowSelectionInterval(0, 0);
    receiverdata_Table.setSelectionBackground(Color.YELLOW);
    }

    Cant resist to point out the ease of doing something like this in Swingx <g>
    Basically, the way to go is
    - install a Highlighter with the visual property/ies you want to use for the highlighting effect
    - update its HighlightPredicate (aka: condition for applying the property) as appropriate
    Below is a code snippet (as usual runnable as-is in the context of SwingX test support). The candy is, that the exact same highlighting code is re-usable in JXList, JXTree and (probably, should check) JXComboBox
    Enjoy
    Jeanette
    * Created on 17.12.2010
    package org.jdesktop.swingx.renderer;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    import javax.swing.Timer;
    import javax.swing.table.DefaultTableModel;
    import org.jdesktop.swingx.InteractiveTestCase;
    import org.jdesktop.swingx.JXTable;
    import org.jdesktop.swingx.decorator.AbstractHighlighter;
    import org.jdesktop.swingx.decorator.ColorHighlighter;
    import org.jdesktop.swingx.decorator.ComponentAdapter;
    import org.jdesktop.swingx.decorator.HighlightPredicate;
    public class DynamicHighlighterExperiments extends InteractiveTestCase {
        public void interactiveHighlightOnInsert() {
            final JXTable table = new JXTable(10, 4);
            final ColorHighlighter hl = new ColorHighlighter(HighlightPredicate.NEVER,
                    Color.YELLOW,  null);
            table.addHighlighter(hl);
            final List<Integer> recentRows = new ArrayList<Integer>();
            ActionListener l = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int insertedRow = table.getModel().getRowCount();
                    recentRows.add(insertedRow);
                    ((DefaultTableModel) table.getModel()).addRow(new Object[] {insertedRow});
                    table.scrollRowToVisible(table.convertRowIndexToView(insertedRow));
                    updateHighlighter(hl, recentRows, insertedRow);
            Timer insertTimer = new Timer(500, l);
            insertTimer.start();
            showWithScrollingInFrame(table, "highlight inserted rows");
        protected void updateHighlighter(final AbstractHighlighter hl,
                final List<Integer> recentRows, final Integer row) {
            hl.setHighlightPredicate(new RowHighlightPredicate(recentRows));
            ActionListener l = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    recentRows.remove(row);
                    hl.setHighlightPredicate(new RowHighlightPredicate(recentRows));
                    ((Timer) e.getSource()).stop();
            Timer removeTimer =  new Timer(1500, l);
            removeTimer.setRepeats(false);
            removeTimer.start();
        // PENDING JW: move into swingx zoo of predicates
        public static class RowHighlightPredicate implements HighlightPredicate {
            List<Integer> rows;
            public RowHighlightPredicate(Collection<Integer> row) {
               rows = new ArrayList<Integer>(row);
            @Override
            public boolean isHighlighted(Component renderer,
                    ComponentAdapter adapter) {
                int modelRow = adapter.convertRowIndexToModel(adapter.row);
                return rows.contains(modelRow);
        public static void main(String[] args) {
            DynamicHighlighterExperiments test = new DynamicHighlighterExperiments();
            try {
                test.runInteractiveTests();
            } catch (Exception e) {
                e.printStackTrace();
    }

  • JTable row background change - based on EXTERNAL event

    Greetings folks!
    I'm hoping for some help with a JTable issue. Here's the scenario:
    The app is a point of sale application. The user scans or manually adds an item to the order, which causes a row to appear in the JTable displaying description, price, quantity, etc. The user can then right click a row on the JTable and select an option from the popup menu. If the user selects one of the options, I want to be able to change the background color on that row.
    EVERYTHING I've seen online and researching is based on adding a custom renderer to the jtable which changes the background based on the data in the row. In my case there isn't anything in the row which changes... hence the point of changing the color.
    What I'm looking for is a method which will let me change the background of row x. I'm guessing there isn't a way. I'm hoping someone has a suggestion.
    Thanks in advance,
    John E.
    PS: I'm fairly new to java and working with inherited code, so please no 'you need to redesign the world' type answers unless there's an easier way. :)

    In my case there isn't anything in the row which changesThen how is the table going to know what color to paint the row? Remember painting the row is a dynamic process. You can't just paint it once. You need the ability to repaint the row if for example the table is scrolled and the row is now longer present. Then when the table scrolls again and the row is present you need to be able to repaint the row in your specified color. This means you need some way to tell the table what color the row should be. Which means you need to keep that information somewhere.
    One way to do this is to store the data in the TableModel that indicates that this row should be painted a "different" color. Then your situation is like the examples you have found. You now have some data you can test. This column does not need to be visible in the table since you can remove the TableColumn from the TableColumnModel so the column is not painted.
    Here is a simple posting that shows a better approach to painting row backgrounds withouth using a renderer:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=610474

  • How to set JTable row background color

    Hello,
    I have seen JTable with rows having alternate background color (mostly white and light blue). How can i set the same.
    Thanks,
    Deepak

    Well, i am new user to forum and so have no idea if this question has been asked previously "countless" times.Which is why you "search first" and "ask later". How to you expect to find out what valuable information is in the forum without learning how to do a simple search. This goes for any forum on the web you might use, so don't use the "I'm a new user" excuse.

  • JTable cell Background Color problem

    I overriden the table renderer and tried to chenge the color of only that row which has greater value in the third column. I coded the logic but it set the color of all the rows. The custom tablecellrendere code is as follows
          public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus, int row, int column)
                cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                   if(vuti[0]==0)
                        //cell.setBackground(Color.pink);
                        vuti[0]=counter;
                   else
                        if (counter>vuti[0] && !isSelected)
                          vuti[0]=counter;
                          cell.setBackground(Color.lightGray);
                      else if(counter<vuti[0])
                        cell.setBackground(Color.white);
                return cell;
          }

    In the code that sets the background, you have a if - else (if - else if) structure. What's the default setting, when none of the 3 conditions are met?
    And learn to indent your code correctly so that code blocks are readily apparent.
    [http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html]
    db

  • Problem in setting the background color of jtable with Nimbus

    Hi
    I have created a java swing application. In which I am using JTable.
    When creating a simple JTable and displaying with Nimbus, the row background color alternates between white and a light blue-grey.
    I want the table with single colour. Only the first column should be grey colour and other should be white.
    I used this code to set the background and foreground colour.
    public Component prepareRenderer
        (TableCellRenderer renderer, int index_row, int index_col){      
                Component objComponent = super.prepareRenderer(renderer, index_row, index_col);         
                Color objGreyColour = new Color(240,240,240);
                Color objWhiteColour = new Color(255,255,255);
                if(index_col == 0){
                    objComponent.setBackground(objGreyColour);
                    objComponent.setFont(new java.awt.Font(CommonClass.getFontName(),java.awt.Font.BOLD, CommonClass.getFontSize()));
                    objComponent.setForeground(Color.BLACK);
                }else{               
                    setSelectionBackground(Color.BLUE);
                    objComponent.setBackground(objWhiteColour);
                    objComponent.setForeground(Color.BLACK);
                return objComponent;
            } Look wise it is fine but when i try to select the cell it is not highlighting the cell and also i m not able to select multiple cell with ctrl key.
    Any help would be appreciated
    Thanks
    Sonal

    Hello,
    1) if you want better help soone,r please post an SSCCE (http://sscce.org) instead of a code extract.
    2) selection highlighting is lost because your code... doesn't handle selection. To take selection into account, you can use <tt>if (super.isRowselected(index_row)) {...}</TT>.
    Regards,
    J.

  • Set Background color of columns in JTable

    Hi,
    I would like to set the background color of columns, which are not editable, to a grey color.
    I have a JTable with 8 columns where the first is not editable (set through a TableModel.
    Regards
    Thomas

    one can use a most efficient method of changing looks of table data by overidding prepareRenderer() method of JTable. this method returns a component which JTable uses to display a cell. a solution could be
    public class mytable extends JTable
       public component prepareRenderer(.......)
            component c = super.prepareRenderer(....);
             if ( not_my_column )
                return c;
            c.setBackground(Color.grey);
            return c;
    }

Maybe you are looking for

  • Issue with submitting podcast.

    I recently submitted my podcast to the itunes store. As far as I know, everything was fine with the RSS feed. I was sent a rejection notice, so I went to look back, and realized that something within the description had come through screwy in the fee

  • The merge process could not allocate memory for an operation; your system may be running low on virtual memory. Restart the Merge Agent.

    I encountered this problem on our SQL2012 and I have tried different scenarios (see below) to no avail. I have decided to give up and check if someone here has encountered this and resolved it.  One thing I know, it's not a memory issue. Both servers

  • DW CS5.5 Won't Open on WinXP Machine

    Yesterday, DW froze during use. I killed the process through Task Manager and since then I cannot open DW. I get as far as loading server behaviors in the opening splash frame and then it hangs. I re-installed DW and still no luck. I now plan to comp

  • Subcontract process (57F4 challan)

    Dear SAP Guru, I implement a scenerio of subcontracting. A new requiremnt is come under subcontracting. i.e A plant send a Material X to subcontractor through 57F4 Challan. And soncontracotr process that material and add some material with X (i.e. Ex

  • Never seen this message before in disk utility after repair perm

    as an idiot I did th enew update and repaired permission hoping that that long hang up would go away and now it said this Repairing permissions for "Macintosh HD" 2008-02-18 22:27:46 -0500: ACL found but not expected on "Applications/Utilities". 2008