Java 验证并突出显示JTable单元格

Java 验证并突出显示JTable单元格,java,swing,jtable,tablecellrenderer,Java,Swing,Jtable,Tablecellrenderer,我根据验证突出显示JTable单元格。在某些情况下,我必须取其他列的值。例如,如果column2包含USA,则column3应仅为数字。另一个例子是,如果col2为“USA”且col4为数字,则col5应仅为三个字符。有人能建议怎么做吗 在下面的片段中,col3包含国家名称col4和col5取决于col3。当我在案例3和案例4中时,我无法检查案例2的值。例如,我想要像,if(col3.value==“USA”) @kleopatra和@mKorbel是正确的。您的片段不完整,但看起来好像您正在尝

我根据验证突出显示
JTable
单元格。在某些情况下,我必须取其他列的值。例如,如果
column2
包含USA,则
column3
应仅为数字。另一个例子是,如果
col2
为“USA”且
col4
为数字,则
col5
应仅为三个字符。有人能建议怎么做吗

在下面的片段中,
col3
包含国家名称
col4
col5
取决于
col3
。当我在
案例3
案例4
中时,我无法检查
案例2
的值。例如,我想要像,
if(col3.value==“USA”)


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

您可以在自定义的
TableCellEditor
中验证输入的值,如下所示。您可以处理
表格模型
中的相关列,如下所示

在评论中,你会说,“如果我没有错的话,需要所有行的循环,对吗?”

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


有关更多详细信息,请参阅。

到底是什么问题?只需用代码表达您的描述。。。顺便说一句:注意行/列坐标区域视图-在将任何与模型相关的逻辑建立在它们之上之前,您必须转换它们1)使用
prepareRenderer
2)删除
开关(col){
3)或kleopatra,我已经编辑了我的问题Mkorbel,如果我没有错的话,prepareRenderer需要所有行的循环,对吗?使用当前的渲染器是不可能的。我应该能够得到其他列的值。谢谢1)使用prepareRenderer 2)移除开关(col){3)为ColumnRenderer切换ColumnReordering,4)在模型或视图中进行任何更改后必须调用渲染器,5)必须选中convertXxxIndexToXxx()
    [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]