gpt4 book ai didi

java - 单击按钮后如何更改 JTable 行的颜色

转载 作者:行者123 更新时间:2023-12-01 11:01:50 24 4
gpt4 key购买 nike

我想在单击按钮后更改 JTable 行的颜色。我发现了许多示例,这些示例展示了如何启动具有不同行颜色的表,以及如何在选择行时更改颜色。但是,我想知道单击 JButton 时更改颜色的正确方法是什么。

TableCellRenderer colorRenderer = new ColorRenderer();
table.setDefaultRenderer(String.class, colorRenderer);

private class ColorRenderer extends DefaultTableCellRenderer {

private static final long serialVersionUID = 1L;

@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (hasFocus) {
setBackground(Color.cyan);
} else if (isSelected) {
setBackground(table.getSelectionBackground());
} else {
setBackground(table.getBackground());
}
return this;
}
}

最佳答案

考虑到您正在 JTable 中加载数据:

public void fillTable(){
List<String> columns = new ArrayList<String>();
List<String[]> values = new ArrayList<String[]>();
columns.add("col1");
columns.add("col2");
columns.add("col3");
for (int i = 0; i < 100; i++) {
values.add(new String[] {"val"+i+" col1","val"+i+" col2","val"+i+" col3"});
}
TableModel tableModel = new DefaultTableModel(values.toArray(new Object[][] {}), columns.toArray());
tableName.setModel(tableModel);
}

然后,您可以使用此类来将渲染设置为JTable:

public class EvenOddRenderer implements TableCellRenderer {

public static final DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();

public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
DEFAULT_RENDERER.setHorizontalAlignment(JLabel.CENTER);
Component renderer = DEFAULT_RENDERER.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
((JLabel) renderer).setOpaque(true);
Color foreground, background;
Color alternate = new Color(0xC0, 0xC0, 0xF0);
Color lightBlue = new Color(204, 204, 255);

if (isSelected) {
foreground = Color.black;
background = Color.gray;
} else {
if (row % 2 == 0) {
foreground = Color.black;
background = Color.white;
} else {
foreground = Color.black;
background = lightBlue;
}
}
renderer.setForeground(foreground);
renderer.setBackground(background);
return renderer;
}
}

像这样:

  TableCellRenderer renderer = new EvenOddRenderer();
tableName.setDefaultRenderer(Object.class, renderer);
tableName.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

JTable on load

然后您可以使用setRowSelectionInterval()方法来选择任意行:

     private void btn(java.awt.event.ActionEvent evt) { 
int index = 0;
tableName.setRowSelectionInterval(index, index);
}

此处您选择 JTable 中的第一行

JTable after button click

在此示例中,您选择 Color.gray 作为 JTable 选择颜色

你肯定可以改变它

关于java - 单击按钮后如何更改 JTable 行的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277361/

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