Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JTable cell coloring problem..help please

 
Jay Mistry
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am trying to color cells depending on the value of the data withing the table. The following is my code, there is only one problem, when I run it it colors the cells but doesn't display the data
================================================================
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
class MyTableCellRender extends DefaultTableCellRenderer {
public MyTableCellRender() {
setOpaque(true);
}

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

String number = (String)value;
int val = Integer.parseInt(number);
if(val > 5){
if(val >= 10) {
setForeground(Color.black);
setBackground(Color.red);
}
else {
setForeground(Color.black);
setBackground(Color.yellow);
}
}else{
setBackground(Color.white);
setForeground(Color.black);
}
return this;
}
}
================================================================
import javax.swing.*;
import javax.swing.table.*;
public class test extends JFrame{

String[][] data = { {"0","0","5","1","0","12"}, {"5","0","2","8","0","0"}, {"50","5","0","8","0","0"}, {"8","0","0","0","5","0"}, {"0","0","8","9","0","10"} };

Object[] fields = {"aaa", "bbb", "ccc", "ddd", "eee", "fff"};

public test() {
setSize(500,135);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocation(200,200);

DefaultTableModel myModel = new DefaultTableModel(data, fields);
JTable myTable = new JTable(myModel);
myTable.setDefaultRenderer(Object.class, new MyTableCellRender());
JScrollPane x = new JScrollPane(myTable);
getContentPane().add(x);
show();
}

public static void main(String args[]) {
test t = new test();
}
}
===============================================================
please help
thank you
 
Javaoops
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Add the statement in
setText(value !=null ? value.toString() : "");
in the method
public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column)

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic