我有這個代碼,我想用不同的顏色給每個單元格着色,例如我想用紅色和紅色單元格編號爲1,2以及用紅色單元格編號爲1,2等等。如何可能?很多例子,但他們都展示瞭如何在點擊或鼠標點擊時爲單元格着色,而且我不想使用它。提前感謝。如何在JTable示例顏色單元格編號(2,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;
}
}
此問題已在SO上回答了幾十次(請參閱此問題右欄中的「相關」鏈接)。答案總是一樣的:使用自定義的'TableCellRenderer'。 Google「Swing教程JTable渲染器」。 –
[link] http://stackoverflow.com/questions/5673430/java-jtable-change-cell-color –
@Gulliaume Polet,@ Jannis Alexakis ....但這不是我要找的東西??我希望我的當我顯示它時,桌子會被着色 – maddy