gpt4 book ai didi

java - 向 JTable 添加彩色行

转载 作者:行者123 更新时间:2023-12-01 13:48:03 25 4
gpt4 key购买 nike

我有一个要填写的表单和 3 个 chekbox(黄橙红),当我填写表单并选择一种颜色时,我单击一个按钮,该按钮会将所选颜色的行添加到 Jtable 中。我使用了 TableCellRenderer 它可以工作,但是当我执行该操作三到四次时,我将所有行都用选定的复选框着色。如何为每一行设置他的颜色?这是我的代码:

JTable  table = new JTable(
new DefaultTableModel(new Object[][] {}, columnNames));

TableColumn column1 = table.getColumnModel().getColumn(
0);
column1.setCellRenderer(getRenderer());
TableColumn column3 = table.getColumnModel().getColumn(
1);
column3.setCellRenderer(getRenderer());
TableColumn column2 = table.getColumnModel().getColumn(
2);
column2.setCellRenderer(getRenderer());
String desc = display.getSelectedItem().toString();
DefaultTableModel tm = (DefaultTableModel) table.getModel();

String numcam = num_cam;
String timeStamp = new SimpleDateFormat(
"yyyy-MM-dd--HH:mm:ss").format(Calendar
.getInstance().getTime());

tm.addRow(new Object[] { new String(timeStamp), new String(numcam),
new String(desc) });

table.setModel(tm);

// reinitialiser les boutons apres le click
buttonGroup.clearSelection();
buttonGroup2.clearSelection();

这是我的单元格渲染器代码

  private static TableCellRenderer getRenderer() {
return new DefaultTableCellRenderer() {
/**
*
*/
private static final long serialVersionUID = 1L;

@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Component tableCellRendererComponent = super
.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
tableCellRendererComponent.setBackground(Color.black);
setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
// verification de l couleur du bouton clické
if (yellow.isSelected()) {
tableCellRendererComponent.setForeground(new Color(255,
255, 51));
} else if (orange.isSelected()) {
tableCellRendererComponent.setForeground(new Color(255,
153, 0));
} else if (red.isSelected()) {
tableCellRendererComponent.setForeground(Color.RED);
}

return tableCellRendererComponent;
}
};
}

最佳答案

How to make for every row his colour?

我不清楚这个问题:

  1. 您是否想让每一行都具有相同的颜色?如果是,那么每当您选择新颜色时都需要调用 table.repaint() 。所有行都将使用新颜色重新渲染

  2. 或者,您是否尝试根据添加行时选择的颜色为每一行设置不同的颜色?如果是,那么您需要向 TableModel 添加另一列来存储该行选定的颜色。然后在渲染器中,您需要从 TableModel 获取颜色。

关于java - 向 JTable 添加彩色行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20197670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com