Link to home
Start Free TrialLog in
Avatar of pml_siva
pml_siva

asked on

How to change single row color on JTable

i am using JTable in my program.during the running time i like to change single row color.how to change..can u give some ideas immediately..bz it's very urgent.
Thankingyou  
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Use a custom cell renderer
Use your own TableCellRenderer (extending the DefaultTableCellRenderer):

public class MyColorCellRenderer extends DefaultTableCellRenderer {

    private int rowToColor = -1;

    public MyColorCellRenderer() {
    }

    public void setRowToColor(int row) {
        rowToColor = row;
    }

    Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

         if (rowToColor!=-1 && row==rowToColor)
            setForeground(Color.RED);
         return super.getTableCellRenderer(table, value, isSelected, hasFocus, row, column);          
    }
}

MyColorCellRenderer myRenderer = new MyColorCellRenderer();
yourTable.setCellRenderer( myRenderer );

To change a row's color:

myRenderer.setRowToColor(5);  // for the 6th row
Typo:

Change

           setForeground(Color.RED);

into

          setBackground(Color.RED);
ASKER CERTIFIED SOLUTION
Avatar of lowenbrausat
lowenbrausat

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lowenbrausat
lowenbrausat

Just a few more lines....
I've done this method and classes to let the user select a BG color from a JColorChooser. Add all this methods and inner clases to the original MyJTable class posted before. Add them at the end of the class, but before the closing '}'.

  private JPopupMenu createPopupMenu()
  {
    String menuName = (getSelectedRows().length == 1)?"Paint Row "+(getSelectedRow()+1):"Paint Selected Rows";
    JMenuItem newBGColorItem = createMenuItem(menuName, new ShowColorChooserAL(this));
    JPopupMenu popup = new JPopupMenu();
    popup.add(newBGColorItem);
    return popup;
  }

  private JMenuItem createMenuItem(String menuName, java.awt.event.ActionListener listener)
  {
    JMenuItem jm = new JMenuItem(menuName);
    jm.addActionListener(listener);
    return jm;
  }

/////INNER CLASSES TO MAMAGE EVENTS/////

  class MyJTableMouseListener extends MouseAdapter
  {
    public void mouseClicked(MouseEvent e)
    {
      if(e.getButton() == MouseEvent.BUTTON3)//right button
      {
          createPopupMenu().show((MyJTable)e.getSource(), e.getX(), e.getY());
      }
    }
  }


  class ShowColorChooserAL implements ActionListener
  {
    private MyJTable parentComp;

    public ShowColorChooserAL(MyJTable c)
    {
      parentComp = c;
    }

    public void actionPerformed(ActionEvent e)
    {
      JColorChooser jcc = new JColorChooser();
      Color selColor = jcc.showDialog(parentComp, "Choose BG Color", Color.white);
      if(selColor != null)
      {
        int[] selectedRows = parentComp.getSelectedRows();
        for(int i=0; i<selectedRows.length; i++)
        {
          parentComp.addRowToPaint(selectedRows[i], selColor);
        }
      }
    }
  }


Finaly, add this line in the constructor of MyJTable class:    this.addMouseListener(new MyJTableMouseListener());

By the way, you'll need to modify the "imports" to compile the class with this modifications.
You'll need javax.swing.JPopupMenu; javax.swing.JMenuItem; javax.swing.JColorChooser; java.awt.event.*;


At Run-Time, select one or more rows and press the right mouse button. You'll see a popup menu with one menu item.
This menu item will open a JColorChooser. Select a color, OK button and thats it!! The selected rows will have a new BG Color.
Hope this is what you are looking for...!
cya!


>>The solution posted by zzynx is heading you in the right way, however you’ll face a few problems if you use it just like it is…!
>>Tables usually need to render different data types so you’ll need different cell renderers.
>>You’ll probably need a checkbox cell render to show Boolean or Bit data,
The default renderer IS a check box in case of a boolean

>>ComboBox cell render to show a list of fixed possibilities, etc.

1) If the author doesn't need special renderers my solution will work OK.

2) If he uses special renderers for specific columns then it's easy to adapt them:

           private int rowToColor = -1;

           public void setRowToColor(int row) {
               rowToColor = row;
           }

           if (rowToColor!=-1 && row==rowToColor)
               setBackground(Color.RED);

3) In this case - of using special renderers - I like the idea of remembering the row to color centralized.
    But I wouldn't do that in your own extension of the JTable, but in my own extension of TableModel.

    Then the above becomes:
           int rowToColor = ( (MyOwnTableModel) table.getModel() ).getRowToColor();
           if (rowToColor!=-1 && row==rowToColor)
               setBackground(Color.RED);
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus,int row,int col)
{

    String s = table.getModel().getValueAt(row,col).toString();

    if(s.equalsIgnoreCase("Fail")) {
         setForeground(Color.red);
    }else {
         setForeground(null);
    }
   
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
row, col);

}