In my application, I am reading a .xml file and writing the data in a JTable. Apart from the data for the table, the .xml file contains an attribute defining the background color of each row. My method for cell rendering looks something like this:
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col) {
JComponent comp = new JLabel();
if (null != value) {
//reading the data and writing it in the comp
}
GenericTableModel model = (GenericTableModel) table.getModel();
GenericObject go = model.getRowObject(row);
Color test = new Color(255, 255, 255);
if (go.getValueByName("COLOR") == null){
}else{
test =(Color) go.getValueByName("COLOR");
}
comp.setBackground(test);
return comp;
}
The .xml file is initialized within the program. My problem is that I don’t know how to define the color in the file so that the variable test will be able to save it as a color. I tried writing it as “Color.white”, “white” and even “255, 255, 255” but i get a casting error when I try saving it in the variable.
Any ideas as to how could I define the color in the file?
I take it that GenericObject#getValueByName() returns a string, right? In that case you need to convert the string to something that can be used to create a Color instance. Assuming that the string is “R,G,B”, then split the string on the comma, convert each component to an integer and create a color:
The other alternative is to define the color field with color names matching the predefined static fields in Color (Color.BLACK, Color.RED, etc), and use reflection to get the correct field, but I leave that as an excercise.