Changing JTable Row Color OnMouseOver

Hello everybody,
is it possible to change JTable Row Color when Mouse passes over it ??
THanks!

Yes...
You have to override the table cell renderer and set the color of the rows based on flag.
The flag can be turned on/off in a mouse motion listener of the table.

Similar Messages

  • JTable row color based on a certain value

    Can anyone please show some code on how
    I can change the background color of an entire
    row based on a string value from the first column ?
    Every time that the first column contains the
    string "TOTAL", I want the entire row to have
    another background color.
    Thanks a lot

    Override getTableCellRendererComponent in Table celll renderer.
    public class MyTableCellRenderer extends DefaultTableCellRenderer
    public MyTableCellRenderer()
    super();
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    Component comp = super.getTableCellRendererComponent(table, value, isSelected,
    hasFocus, row, column);
              ((JLabel)comp).setOpaque(true);
    if(value.equals("TOTAL")
    comp.setBackGround(color);
    else
    set whatever the default background color

  • Change the row colors based on column values in MOSS 2007.

    Hi Team,
    I am using MOSS 2007 environment. In that I am having one SharePoint list. In that list based on column values rows colors need to change.
    Kindly help me anyone on this.
    Thanks,
    Ashok

    Hi Ashok,
    Please follow the below link:
    http://www.contentmaster.com/sharepoint-2010/conditional-formatting-of-list-views-for-sharepoint-2010-changing-the-font-colour/
    http://sharepoint.stackexchange.com/questions/7478/highlight-row-color-based-on-field-values-in-sharepoint-2010-list-view
    Best Regards,
    Brij K

  • Code to change JTable cell color not working

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

    My code below is supposed to change the color
    of a single JTable cell however its not working.
    Could anyone please tell me why?
    Here's the code:
    import java.awt.*;
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ColorTable extends JTable {
    public ColorTable() {
    AbstractTableModel tableModel = new AbstractTableModel() {
    public Class getColumnClass(int column) { return Integer.class; }
    public int getColumnCount() { return 6; }
    public int getRowCount() { return 10;}
    public Object getValueAt(int row,int col) { return new Integer(row * col); }
    setModel(tableModel);
    setDefaultRenderer(Integer.class,new ColorRenderer(Color.cyan));
    this.setRowSelectionAllowed(false);
    this.setCellSelectionEnabled(true);
    addMouseListener(new MouseAdapter() {
    private ColorRenderer renderer;
    private JColorChooser chooser = new JColorChooser();
    public void mousePressed(MouseEvent e) {
    if(e.getModifiers() == MouseEvent.BUTTON3_MASK) {
    System.out.print("rowAtPoint(e.getPoint())=" +rowAtPoint(e.getPoint()));
    System.out.print( "columnAtPoint(e.getPoint()))=" + columnAtPoint(e.getPoint()));
    renderer = (ColorRenderer)getCellRenderer(rowAtPoint(e.getPoint()), columnAtPoint(e.getPoint()));
    // chooser.setColor(renderer.getColor());
    renderer.setColor(chooser.showDialog((Component)e.getSource(),"Choose Cell Color",chooser.getColor()));
    class ColorRenderer extends DefaultTableCellRenderer {
    private Color cellColor;
    public ColorRenderer(Color color) { cellColor = color; }
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    System.out.print("row= " + row + "\n");
    System.out.print("column= " + column + "\n");
    System.out.print("OBJECT VALUE=" + value.toString());
    //Component comp = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
    if (isSelected) {
    setOpaque(true);
    setBackground(cellColor);
    else {
    setBackground(Color.white);
    setForeground(Color.black);
    return this;
    public void setColor(Color color)
    cellColor = color;
    ColorTable.this.repaint();
    public Color getColor() { return cellColor; }
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    ColorTable table = new ColorTable();
    panel.add(table);
    frame.getContentPane().add(panel);
    frame.setSize(500,250);
    frame.setVisible(true);

  • Changing Subtotal row color

    Hi Experts,
    how can i change the color of sutotals/totals row in a BEx report from default YELLOW to any other color as per clients choice.
    thanks in advance

    hi
    check this thread:
    Re: Color format changes
    cheers
    Sunil

  • How to chang the row's color in the Jtable?

    I have a table and many rows,I want chang the rows color,like row one's color is red,row tow's color is write,row three's color is green.How can do it? And if i want chang row 3,coloum 2's color.How can do it?
    thanks.

    hi,
    I use jdbtable to view data,I want them to chang row color when some cells equal the value.But interface getTableCellRendererComponent not run.I don't know why!
    jdbtable is extend jtable ,it made in borland jbuilder.
    //1 class
    package errorreport;
    import java.awt.Component;
    import java.awt.Color;
    import javax.swing.table.DefaultTableCellRenderer;
    import com.borland.dbswing.*;
    public class rowcolor extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent
    (JdbTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int column)
    Component cell = super.getTableCellRendererComponent
    (table, value, isSelected, hasFocus, row, column);
    int iColcount = 0;
    iColcount = table.getColumnCount();
    if( value instanceof String )
    String strAlmlev = (String)value;
    if(strAlmlev.trim().equals("C1"))
    cell.setBackground( Color.red );
    // You can also customize the Font and Foreground this way
    // cell.setForeground();
    // cell.setFont();
    else
    if(strAlmlev.trim().equals("C2"))
    cell.setBackground( Color.orange );
    else
    if(strAlmlev.trim().equals("C3"))
    cell.setBackground( Color.yellow );
    else
    if(strAlmlev.trim().equals("ERR"))
    cell.setBackground( Color.green );
    return cell;
    //2 class
    JdbTable jdbTable2 = new JdbTable();
    TableCellRenderer renderer = new rowcolor();
    try
    jdbTable2.setDefaultRenderer( Class.forName( "java.lang.String" ), renderer );
    catch( ClassNotFoundException ex )
    System.exit( 0 );
    thanks

  • HOW TO ADD COLORS TO JTABLE ROWS??

    I want to change the colors of alternate rows in my JTable. I am doing so using CellRenderer, but then I am not able to view the selected rows.
    tell me how can I change the row color as well as a selected row should be identifiable from others, as ordinary JTable.
    thanks

    Hi,
    try this:
    define your own DefaultTableCellRenderer like this:
    class MyRenderer extends DefaultTableCellRenderer     {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column){
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if (isSelected) setBackground( Color.anyColor );               
    return this;
    Hope it helps!
    Regards, Paul

  • Dynamically changing row color in an ADF table?

    Hi,
    I am using Build JDEVADF_11.1.1.3.PS2_GENERIC_100408.2356.5660. Can anyone please let me know the code for dynamically changing the row color of an ADF table?
    Thanks,
    Vik

    well you can use EL on af:column inlineStyle property to change the color on condition
    e.g
    inlineStyle='#{(row.SelectedRow)?"background-color: Silver":""};a example can be found here it is changing color based on Checkbox selection http://baigsorcl.blogspot.com/2010/06/deleting-multi-selected-rows-from-adf.html

  • Table row colors alternating

    Hello Everyone,
    I'm trying in the configure properties of a table change the row colors to alternating, but it has no effect.
    It always remains the same formating, i.e., every row with the same blue color.
    I only can set it to alternating if the table is marked in the properties as editable (Editing condition = true). It doesn't make any sense! I do not want the user to change the cells of the table, but still want to use alternating colors, and it is not possible.
    I'm using Visual Composer 7.01 with SP5
    Does anyone have any idea?
    Tanks,
    Diogo Ferreira.

    Hi,
    For messages about VC 7.0 version (this includes 7.01 and 7.02) please refer to the [VC 7.0 forum|SAP NetWeaver Visual Composer;.
    Best regards,
    Tal.

  • Changing View data color

    How can I change the row colors in an updated list or pie chart view to use a certain color based on the value it is reporting?

    Yes this is possible. You can create a calculation that is an HTML code, within the command you can have an If statement to set the color of the field based on its value. Take a look at the Technote for Custom HTML Reports and it will give you an Idea. http://www.oracle.com/technology/products/integration/bam/10.1.3/TechNotes/TechNote_BAM_CustomHTMLReport.pdf

  • Changing background color in JTable, only changes one row at a time...

    I'm trying to change the color of rows when the 5th column meets certain criteria. I think I'm very close, but I've hit a wall.
    What's happening is the row will change color as intended when the text in the 5th column is "KEY WORD", but when I type "KEY WORD" in a different column it will set the first row back to the regular colors. I can easily see why it's doing this, everytime something is changed it rerenders every cell, and the listener only checks the cell that was just changed if it met the "KEY WORD" condition, so it sets every cell (including the previous row that still meets the condition) to the normal colors. I can't come up with a good approach to changing the color for ALL rows that meet the condition. Any help would be appreciated.
    In this part of the CellRenderer:
            if (isSelected)
                color = Color.red;
            else
                color = Color.blue;
            if (hasFocus)
                color = Color.yellow;
            //row that meets special conditions
            if(row == specRow && col == specCol)
                color = color.white; I was thinking an approach would be to set them to their current color except for the one that meets special conditions, but the two problems with that are I can't figure out how to getColor() from the table, and I'm not sure how I would initially set the colors.
    Here's the rest of the relevant code:
        public void tableChanged(TableModelEvent e)
            int firstRow = e.getFirstRow();
            int lastRow  = e.getLastRow();
            int colIndex = e.getColumn();
            if(colIndex == 4)
                String value = (String)centerTable.getValueAt(firstRow, colIndex);
                // check for our special selection criteria
                if(value.equals("KEY WORD"))
                    for(int j = 0; j < centerTable.getColumnCount(); j++)
                        CellRenderer renderer =
                            (CellRenderer)centerTable.getCellRenderer(firstRow, j);
                        renderer.setSpecialSelection(firstRow, j);
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.Component;
    import java.awt.Color;
    public class CellRenderer extends DefaultTableCellRenderer
        int specRow, specCol;
        public CellRenderer()
            specRow = -1;
            specCol = -1;
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus,
                                                       int row, int col)
            setHorizontalAlignment(JLabel.CENTER);
            Color color = Color.green;
            if (isSelected)
                color = Color.red;
            else
                color = Color.blue;
            if (hasFocus)
                color = Color.yellow;
            if(row == specRow && col == specCol)
                color = color.white;
            //setForeground(color);
            setBackground(color);
            setText((String)value);
            return this;
        public void setSpecialSelection(int row, int col)
            specRow = row;
            specCol = col;
    }If I'm still stuck and more of my code is needed, I'll put together a smaller program that will isolate the problem tomorrow.

    That worked perfectly for what I was trying to do, but I've run into another problem. I'd like to change the row height when the conditions are met. What I discovered is that this creates an infinite loop since the resizing triggers the renderer, which resizes the row again, etc,. What would be the proper way to do this?
    Here's the modified code from the program given in the link. All I did was declare the table for the class, and modify the if so I could add the "table.setRowHeight(row, 30);" line.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    public class TableRowRenderingTip extends JPanel
        JTable table;
        public TableRowRenderingTip()
            Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
            Object[][] data =
                {"Buy", "IBM", new Integer(1000), new Double(80.5), Boolean.TRUE},
                {"Sell", "Dell", new Integer(2000), new Double(6.25), Boolean.FALSE},
                {"Short Sell", "Apple", new Integer(3000), new Double(7.35), Boolean.TRUE},
                {"Buy", "MicroSoft", new Integer(4000), new Double(27.50), Boolean.FALSE},
                {"Short Sell", "Cisco", new Integer(5000), new Double(20), Boolean.TRUE}
            DefaultTableModel model = new DefaultTableModel(data, columnNames)
                public Class getColumnClass(int column)
                    return getValueAt(0, column).getClass();
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("Alternating", createAlternating(model));
            tabbedPane.addTab("Border", createBorder(model));
            tabbedPane.addTab("Data", createData(model));
            add( tabbedPane );
        private JComponent createAlternating(DefaultTableModel model)
            JTable table = new JTable( model )
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    //  Alternate row color
                    if (!isRowSelected(row))
                        c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        private JComponent createBorder(DefaultTableModel model)
            JTable table = new JTable( model )
                private Border outside = new MatteBorder(1, 0, 1, 0, Color.RED);
                private Border inside = new EmptyBorder(0, 1, 0, 1);
                private Border highlight = new CompoundBorder(outside, inside);
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    JComponent jc = (JComponent)c;
                    // Add a border to the selected row
                    if (isRowSelected(row))
                        jc.setBorder( highlight );
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        public JComponent createData(DefaultTableModel model)
            table = new JTable( model )
                public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
                    Component c = super.prepareRenderer(renderer, row, column);
                    //  Color row based on a cell value
                    if (!isRowSelected(row))
                        c.setBackground(getBackground());
                        String type = (String)getModel().getValueAt(row, 0);
                        if ("Buy".equals(type)) {
                            table.setRowHeight(row, 30);
                            c.setBackground(Color.GREEN);
                        if ("Sell".equals(type)) c.setBackground(Color.YELLOW);
                    return c;
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            table.changeSelection(0, 0, false, false);
            return new JScrollPane( table );
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        public static void createAndShowGUI()
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("Table Row Rendering");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new TableRowRenderingTip() );
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }Edited by: scavok on Apr 26, 2010 6:43 PM

  • Changing Row Color In JTable !

    Hi friends
    I have two JTables. The first one has 7 columns and 10 rows (with data) but the second one is empty.
    The user can choose one row from first table and by pressing the ((copy)) button , copy that row to the second table. Is it possible to change the color of those rows(in the first table) that been copied to the second table. I mean if the user choose a row and copy then to the second table, the color of this row wold be changed.
    Can anybody help me with that??
    Thanks

    I think you are heading in the wrong direction here... you want to create a brand new DefaultTableCellRenderer and override the getTableCellRendererComponent method...
    public class MyRenderer extends DefaultTableCellRenderer {
      public Component getTableCellRendererComponent(JTable table, Object value,
                              boolean isSelected, boolean hasFocus, int row, int column) {
                  JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                               row, column);
                  //now I can change the background color depending on the row...
                  if (row == xxx) lbl.setBackground(Color.red);
    }Then use your new class on your table...
    <table.setDefaultRenderer(Object.class, new MyRenderer()); //the class must match what you TableModel returns for getColumnClass();Hope this helps,
    Josh Castagno
    http://www.jdc-software.com
    Hope this helps

  • Changing background color in a selected jtable row

    I have a problem when I call fireTableDataChanged() to change the background color in a table.
    If a row is selected neither getTableCellEditorComponent nor getTableCellRendererComponent is called after fireTableDataChanged()...
    As can you see running this:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;   
    //YOU MUST CHANGE IN:
    // import yourpackagename.MyTable.MyTableModel;
    import swing.table.MyTable.MyTableModel;
    public class DemoCellEditor extends javax.swing.JFrame {
         private MyTable myTable1;
         private JScrollPane jScrollPane1;
         private JButton jButton1;
         private AbstractAction abstractAction1;
         static Color red = new Color(200,23,23);
         static Color white = new Color(255,255,255);
         static public Color backgroundColor = white;
         static public Color getBackgroundColor(){ return backgroundColor ;}
         * Auto-generated main method to display this JFrame
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        DemoCellEditor inst = new DemoCellEditor();
                        inst.setLocationRelativeTo(null);
                        inst.setVisible(true);
         public DemoCellEditor() {
              super();
              initGUI();
         private void initGUI() {
              try {
                   GroupLayout thisLayout = new GroupLayout((JComponent)getContentPane());
                   getContentPane().setLayout(thisLayout);
                   setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                        jScrollPane1 = new JScrollPane();
                             myTable1 = new MyTable();
                             jScrollPane1.setViewportView(myTable1);
                        jButton1 = new JButton();
                        jButton1.setText("jButton1");
                        jButton1.setAction(getAbstractAction1());
                   thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
                        .addContainerGap(43, 43)
                        .addGroup(thisLayout.createParallelGroup()
                            .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
                                .addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 151, Short.MAX_VALUE))
                            .addGroup(thisLayout.createSequentialGroup()
                                .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 172, GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap(57, 57));
                   thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
                        .addContainerGap(48, 48)
                        .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 162, GroupLayout.PREFERRED_SIZE)
                        .addGap(78)
                        .addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(111, Short.MAX_VALUE));
                   pack();
              } catch (Exception e) {
                   e.printStackTrace();
         private AbstractAction getAbstractAction1() {
              if(abstractAction1 == null) {
                   abstractAction1 = new AbstractAction("Change color", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if(backgroundColor == white)
                                  backgroundColor = red;
                             else
                                  backgroundColor = white;
                             ((MyTableModel)myTable1.getModel()).fireTableDataChanged();
              return abstractAction1;
    class MyTable extends JTable
         public MyTable()
              setModel(new MyTableModel());
              setDefaultRenderer(Boolean.class, new TickTableCheckBoxRenderer());
              setDefaultEditor(Boolean.class, new TickTableCheckBoxRenderer());
             class MyTableModel extends AbstractTableModel {
                 private String[] columnNames = {"Check box"};
                 private Object[][] data = { {new Boolean(true)},
                                                    {new Boolean(true)},
                                                    {new Boolean(true)},
                                                    {new Boolean(true)}};
                 public int getColumnCount() {
                     return columnNames.length;
                 public int getRowCount() {
                     return data.length;
                 public String getColumnName(int col) {
                     return columnNames[col];
                 public Object getValueAt(int row, int col) {
                     return data[row][col];
                  * JTable uses this method to determine the default renderer/
                  * editor for each cell.  If we didn't implement this method,
                  * then the last column would contain text ("true"/"false"),
                  * rather than a check box.
                 public Class getColumnClass(int c) {
                     return getValueAt(0, c).getClass();
                 public boolean isCellEditable(int row, int col) {
                       return true;
                 public void setValueAt(Object value, int row, int col) {
                     data[row][col] = value;
                     fireTableCellUpdated(row, col);
    class TickTableCheckBoxRenderer extends AbstractCellEditor
         implements TableCellEditor,TableCellRenderer, ActionListener
         JCheckBox checkBox;
         public TickTableCheckBoxRenderer()
              checkBox = new JCheckBox();
             checkBox.setHorizontalAlignment(SwingConstants.CENTER);
             checkBox.addActionListener(this);
         public Component getTableCellRendererComponent(JTable
                                             table, Object value, boolean isSelected, boolean
                                             hasFocus, int row, int column)
         checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
         checkBox.setBackground(DemoCellEditor.getBackgroundColor()); 
         return checkBox;
         public Component getTableCellEditorComponent(JTable table, Object value,
                                       boolean isSelected, int row, int column)
         checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
         checkBox.setBackground(DemoCellEditor.getBackgroundColor()); 
         return checkBox;
         public Object getCellEditorValue()
         return Boolean.valueOf(checkBox.isSelected());
         public void actionPerformed(ActionEvent actionEvent) {
              System.out.println("selected ="+checkBox.isSelected());  
    }Edited by: snoopybad77 on Mar 27, 2010 3:27 PM

    weel pheraps for compilig it is better without inner class:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;    
    public class DemoCellEditor extends javax.swing.JFrame {
         private MyTable myTable1;
         private JScrollPane jScrollPane1;
         private JButton jButton1;
         private AbstractAction abstractAction1;
         static Color red = new Color(200,23,23);
         static Color white = new Color(255,255,255);
         static public Color backgroundColor = white;
         static public Color getBackgroundColor(){ return backgroundColor ;}
         * Auto-generated main method to display this JFrame
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        DemoCellEditor inst = new DemoCellEditor();
                        inst.setLocationRelativeTo(null);
                        inst.setVisible(true);
         public DemoCellEditor() {
              super();
              initGUI();
         private void initGUI() {
              try {
                   GroupLayout thisLayout = new GroupLayout((JComponent)getContentPane());
                   getContentPane().setLayout(thisLayout);
                   setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                        jScrollPane1 = new JScrollPane();
                             myTable1 = new MyTable();
                             jScrollPane1.setViewportView(myTable1);
                        jButton1 = new JButton();
                        jButton1.setText("jButton1");
                        jButton1.setAction(getAbstractAction1());
                   thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
                        .addContainerGap(43, 43)
                        .addGroup(thisLayout.createParallelGroup()
                            .addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
                                .addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 21, GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 151, Short.MAX_VALUE))
                            .addGroup(thisLayout.createSequentialGroup()
                                .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 172, GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap(57, 57));
                   thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
                        .addContainerGap(48, 48)
                        .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 162, GroupLayout.PREFERRED_SIZE)
                        .addGap(78)
                        .addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 130, GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(111, Short.MAX_VALUE));
                   pack();
              } catch (Exception e) {
                   e.printStackTrace();
         private AbstractAction getAbstractAction1() {
              if(abstractAction1 == null) {
                   abstractAction1 = new AbstractAction("Change color", null) {
                        public void actionPerformed(ActionEvent evt) {
                             if(backgroundColor == white)
                                  backgroundColor = red;
                             else
                                  backgroundColor = white;
                             ((MyTableModel)myTable1.getModel()).fireTableDataChanged();
                             myTable1.repaint();
              return abstractAction1;
    class MyTable extends JTable
              public MyTable()
                   setModel(new MyTableModel());
                   setDefaultRenderer(Boolean.class, new TickTableCheckBoxRenderer());
                   setDefaultEditor(Boolean.class, new TickTableCheckBoxRenderer());
    class MyTableModel extends AbstractTableModel {
         private String[] columnNames = {"Check box"};
         private Object[][] data = { {new Boolean(true)},
                                               {new Boolean(true)},
                                               {new Boolean(true)},
                                               {new Boolean(true)}};
         public int getColumnCount() {
             return columnNames.length;
         public int getRowCount() {
             return data.length;
         public String getColumnName(int col) {
             return columnNames[col];
         public Object getValueAt(int row, int col) {
             return data[row][col];
          * JTable uses this method to determine the default renderer/
          * editor for each cell.  If we didn't implement this method,
          * then the last column would contain text ("true"/"false"),
          * rather than a check box.
         public Class getColumnClass(int c) {
             return getValueAt(0, c).getClass();
         public boolean isCellEditable(int row, int col) {
               return true;
         public void setValueAt(Object value, int row, int col) {
             data[row][col] = value;
             fireTableCellUpdated(row, col);
    class TickTableCheckBoxRenderer extends AbstractCellEditor
         implements TableCellEditor,TableCellRenderer, ActionListener
         JCheckBox checkBox;
         public TickTableCheckBoxRenderer()
              checkBox = new JCheckBox();
             checkBox.setHorizontalAlignment(SwingConstants.CENTER);
             checkBox.addActionListener(this);
         public Component getTableCellRendererComponent(JTable
                                             table, Object value, boolean isSelected, boolean
                                             hasFocus, int row, int column)
         checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
         checkBox.setBackground(DemoCellEditor.getBackgroundColor()); 
         return checkBox;
         public Component getTableCellEditorComponent(JTable table, Object value,
                                       boolean isSelected, int row, int column)
         checkBox.setSelected( Boolean.valueOf( value.toString() ).booleanValue() );
         checkBox.setBackground(DemoCellEditor.getBackgroundColor()); 
         return checkBox;
         public Object getCellEditorValue()
         return Boolean.valueOf(checkBox.isSelected());
         public void actionPerformed(ActionEvent actionEvent) {
              System.out.println("selected ="+checkBox.isSelected());  
    }Edited by: snoopybad77 on Mar 27, 2010 5:20 PM

  • Change JTable's row color on row selection

    Hello!
    Everywhere I've looked they're only explaining how to draw rows in different colors WHEN THE TABLE IS BEING CREATED, via prepareRenderer.
    But that is not what I am looking for. What I want is to actually change the row's color after the table has been drawn/rendered/whatsoever. For instance, when the user clicks on that row. The default behaviour is for the row to become blueish, but, when the user selects another row, the first selected row turns back to white. I would like to prevent that from happening. I want the row to become FIRE RED when the user clicks on it, and I want the row to remain like that for good, even when the user selects a different row. Do I make any sense here? :-)
    Thank you for your time and future suggestions.

    Everywhere I've lookedApparently you didn't look in the Swing forum, because thats where Swing related questions should be posted.
    but how do I assign a cell renderer to an entire row/table ?The easiest way is to use the prepareRenderer(...) method you have already found. My "TablePrepareRenderer" class (which you can find by searching the Swing forum) shows you how to do this.
    You will note that the color of the row is determined by data in the table. So all you need to do is add another column in the TableModel that contains the information you need to determine the row color. That column can be removed from view in the table by removing the TableColumn from the TableColumnModel.

  • 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

Maybe you are looking for

  • Email not updating on iOS devices

    I have my regular email account and the iCloud account set up for my iPhone and iPad. Last Wednesday the iCloud account stopped updating my emails. The other account (embarqmail) is fine, just the iCloud account. I can't seem to find any settings hav

  • How can I recover and unlink my contacts?

    I accidentally linked several cards in Contacts. I failed to unlink them, deleting the linked card as a frustrated final resort, doing nothing but losing me all those contacts. How can I recover and unlink these cards?

  • Logic 9.16 crashes all the time when brought back to front

    Here is the crash log: Has anybody any idea what I can do? Ernst Date/Time:       2012-02-23 17:29:38 +0100 OS Version:      10.7.3 (Build 11D50b) Architecture:    x86_64 Report Version:  9 Command:         Logic Pro Path:            /Applications/Lo

  • Mail attachments as MIME-attachment unreadable!!!

    I've been using Entourage for a long time and it works ok I have a gmail account Now I'm trying to synchronize my mail with an IMAP account in Apple Mail app. The problem is that some of the attachments now appear as "MIME-attachment" and they are un

  • Autoview Enovia Integration-JVue: Missing resource com.cimmetry.core.DMSRem

    hi we are getting below error in autoVue. This is integrated with Enovia V6r2012x. JVue: Missing resource com.cimmetry.core.DMSRemoteException: Unable to read a file from directory in com.cimmetry.vueframe.resources.VueFrame (Locale=debug_DEBUG) Log