Shading part of a JTable Cell dependent upon the value of the cell
Hi
Was hoping some one woudl be able to provide some help with this. I'm trying to create a renderer that will "shade" part of a JTable cell's background depending upon the value in the cell as a percentage (E.g. if the cell contains 0.25 then a quarter of the cell background will be shaded)
What I've got so far is a renderer which will draw a rectangle whose width is the relevant percentage of the cell's width. (i.e. the width of the column) based on something similar I found in the forum but the part I'm struggling with is getting it to draw this rectangle in any cell other than the first cell. I've tried using .getCellRect(...)
to get the x and y position of the cell to draw the rectangle but I still can't make it work.
The code for my renderer as it stands is:
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
publicclass PercentageRepresentationRendererextends JLabelimplements TableCellRenderer{
double percentageValue;
double rectWidth;
double rectHeight;
JTable table;
int row;
int column;
int x;
int y;
public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected,boolean hasFocus,int row,int column){
if (valueinstanceof Number)
{
this.table = table;
this.row = row;
this.column = column;
Number numValue = (Number)value;
percentageValue = numValue.doubleValue();
rectHeight = table.getRowHeight(row);
rectWidth = percentageValue * table.getColumnModel().getColumn(column).getWidth();
}
returnthis;
}
publicvoid paintComponent(Graphics g){
x = table.getCellRect(row, column,false).x;
y = table.getCellRect(row, column,false).y;
setOpaque(false);
Graphics2D g2d = (Graphics2D)g;
g2d.fillRect(x,y,new Double(rectWidth).intValue(),new Double(rectHeight).intValue());
super.paintComponent(g);
}
}
and the following code produces a runnable example:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
publicclass PercentageTestTableextends JFrame{
public PercentageTestTable()
{
Object[] columnNames =new Object[]{"A","B"};
Object[][] tableData =new Object[][]{{0.25,0.5},{0.75,1.0}};
DefaultTableModel testModel =new DefaultTableModel(tableData,columnNames);
JTable test =new JTable(testModel);
test.setDefaultRenderer(Object.class,new PercentageRepresentationRenderer());
JScrollPane scroll =new JScrollPane();
scroll.getViewport().add(test);
add(scroll);
}
publicstaticvoid main(String[] args)
{
PercentageTestTable testTable =new PercentageTestTable();
testTable.pack();
testTable.setVisible(true);
testTable.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
If anyone could help or point me in the right direction, I'd appreciate it.
Ruanae

