我有这个代码,我想用不同的颜色为每个单元格着色,例如,我想用红色给单元格编号 1,1 着色,用浅红色给单元格编号 1,2 着色等等。这怎么可能?我经历了很多例子但他们都展示了如何在鼠标点击或鼠标点击时为单元格着色,我想要它。提前致谢。
package test;
public class ModelJTable extends JFrame {
private DefaultTableModel model;
private JTable table;
public ModelJTable() throws IOException {
super();
model = new DefaultTableModel();
model.addColumn("price");
model.addColumn("quantity");
model.addColumn("buy");
model.addColumn("sell");
String array[][] = new String[6][6];
array[0][0] = "35";
array[0][1] = "1";
array[0][2] = "2";
array[1][0] = "34";
array[1][1] = "2";
array[1][2] = "3";
array[2][0] = "37";
array[2][1] = "2";
array[2][2] = "6";
array[3][0] = "33";
array[3][1] = "7";
array[3][2] = "8";
array[4][0] = "34";
array[4][1] = "9";
array[4][2] = "4";
array[5][0]="35";
array[5][1]="9";
array[5][2]="6";
String mainarray[][] = new String[6][6];
//copy all elements of array to mainarray
for(int i=0;i<5;i++)
{
String temp[]={""};
model.addRow(temp);
}
for (int i = 5; i < 10; i++) {
model.insertRow(i, array[i-5]);
// System.out.print(mainarray[i][j]+" ");
}
table = new JTable(model);
JTextField textBox=new JTextField();
TableColumn soprtColumn=table.getColumnModel().getColumn(1);
soprtColumn.setCellEditor(new DefaultCellEditor (textBox));
table.setCellSelectionEnabled(true);
textBox.setBackground(Color.RED);
JPanel inputPanel = new JPanel();
inputPanel.add(addButton);
inputPanel.add(removeButton);
Container container = getContentPane();
container.add(new JScrollPane(table), BorderLayout.CENTER);
container.add(inputPanel, BorderLayout.NORTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public static void main(String args[]) throws IOException {
new ModelJTable();
}
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
Component cell = model.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, column);
if( value instanceof Integer )
{
Integer amount = (Integer) value;
if( amount.intValue() < 0 )
{
cell.setBackground( Color.red );
// You can also customize the Font and Foreground this way
// cell.setForeground();
// cell.setFont();
}
else
{
cell.setBackground( Color.white );
}
}
return cell;
}
}