1

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

在下面的片段中,col3包含国家名称; col4col5依赖col3. 当我在case 3和 中时case 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]
4

1 回答 1

2

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

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

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

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

有关更多详细信息,请参阅概念:编辑器和渲染器

于 2012-02-18T16:04:52.530 回答