0

I have a JTable 5x5, and I want to write a procedure setColorTable(JTable table, int Row, int Col), when call Procedure setColorTable it will setBackground color for row and col in table. everyone can help me.

thank you so much.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 2
    Please at least try writting some code and post it if you still have a problem. – dngfng Oct 17 '12 at 09:14
  • have a look at a) the tutorial referenced in the swing tag wiki b) older QAs referenced f.i. at the sidebar of the question c) do some research and try out what you find ... – kleopatra Oct 17 '12 at 09:36

3 Answers3

1

You'll have to create a custom TableCellRenderer that extends a Swing Component (JLabel will probably suit your needs if you only want to change the colour), and implements the TableCellRenderer interface.

Try reading this or the JavaDoc

mdhillman
  • 91
  • 1
  • 6
1

You can write your own class by extending javax.swing.table.DefaultTableCellRenderer and then overide the following method as you wish.

public class MyNewCellRenderer extends DefaultTableCellRenderer
{
@Override
    public Component getTableCellRendererComponent(
            JTable table, Object object,
            boolean isSelected, boolean hasFocus,
            int row, int column)
    {
        JLabel label = (JLabel) super.getTableCellRendererComponent(table, object, isSelected, hasFocus, row, column);
  label.setBackground(Color.WHITE);
    }
}

Finally atatch the TableCellRenderer by;

jTable1 = new javax.swing.JTable()
{
    public TableCellRenderer getCellRenderer(int row, int column)
    {
        return new MyNewCellRenderer();
    }
};
Anuruddha
  • 1,367
  • 6
  • 19
  • 38
  • 2
    basically correct, just beware: due to a bug in DefaultTableCellRenderer this will not be quite good enough - for details see a [recent QA](http://stackoverflow.com/q/9607670/203657) – kleopatra Oct 17 '12 at 09:40
1

how to change color of rows in JTable

for coloring (Font, Foregroung, Backgroung, e.i.) whole row is there prepareRenderer

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319