gpt4 book ai didi

java - 验证并突出显示 JTable 单元格

转载 作者:行者123 更新时间:2023-11-30 04:53:28 25 4
gpt4 key购买 nike

我根据验证突出显示 JTable 单元格。在某些情况下,我必须采用其他列的值。例如,如果 column2 包含 USA,则 column3 应该只是数字。另一个例子,如果 col2 是“USA”并且 col4 是数字,那么 col5 应该只有三个字符。有人可以建议如何做到这一点吗?

在下面的片段中,col3 包含国家/地区名称; col4col5 依赖于 col3。当我处于 case 3case 4 时,我无法检查 case 2 的值。例如,我想要 if (col3.value == "USA")

    [code]
tcol = editorTable.getColumnModel().getColumn(0);
tcol.setCellRenderer(new CustomTableCellRenderer());

tcol = editorTable.getColumnModel().getColumn(1);
tcol.setCellRenderer(new CustomTableCellRenderer());

tcol = editorTable.getColumnModel().getColumn(2);
tcol.setCellRenderer(new CustomTableCellRenderer());

public class CustomTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent (JTable table, Object
value,boolean isSelected, boolean hasFocus, int row, int col){

Component cell = super.getTableCellRendererComponent(table, value,
isSelected,hasFocus, row, col);

if (value instanceof String) {
String str = (String) value;

switch (col) {
case 0:
col1(str, cell);
break;
case 1:
col2(str, cell);
break;
case 2:
col3(str, cell);
break;
}
}
return cell;
}

private void col1(String str, Component cell) {
if(!str.matches("[0-9a-zA-z]")){
cell.setBackground(Color.RED);
} else {
cell.setBackground(Color.GREEN);
}
}

private void col2(String str, Component cell) {
if(!str.matches("[A-Z]{3}")){
cell.setBackground(Color.RED);
} else {
cell.setBackground(Color.GREEN);
}
}
[/code]

最佳答案

@kleopatra 和 @mKorbel 是正确的。您的片段不完整,但看起来就好像您正在尝试解决渲染器中的编辑器和模型问题。

您可以在自定义 TableCellEditor 中验证输入的值,如 example 所示。 。您可以处理 TableModel 中的依赖列,如 example 所示。 .

在评论中,您说:“如果我没记错的话,prepareRenderer() 需要循环所有行,对吧?”

不,JTable “内部实现始终使用此方法来准备渲染器,以便子类可以安全地覆盖此默认行为。”当必须有选择地将更改应用于所有渲染器时,覆盖 prepareRenderer() 最有用。

参见Concepts: Editors and Renderers了解更多详情。

关于java - 验证并突出显示 JTable 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9340206/

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