2012-02-18 92 views
1

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

在以下片段中,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] 
+0

究竟是什么问题?简单地用代码表示您的deescription ...顺便说一句,注意行/列坐标区_view_ - 在基于任何模型相关的逻辑之前,您必须将它们转换为 – kleopatra 2012-02-18 10:07:16

+0

1)使用'prepareRenderer' 2)移除'switch (col){'3)[简化代码](http://stackoverflow.com/questions/7132400/jtable-row-hightlighter-based-on-value-from-tablecell)或[here](http:// stackoverflow .COM /问题/ 6410839 /亮点 - 子 - 在最tablecells-使用换的JTable-filetering这 - 是 - ) – mKorbel 2012-02-18 10:43:32

+0

克列奥帕特拉,我已经编辑我的问题 – FirmView 2012-02-18 13:13:19

回答

2

@kleopatra和@mKorbel是正确的。你的片段是不完整的,但它出现就好像你正试图解决渲染器中的编辑器和模型问题。

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

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

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

详情请参阅Concepts: Editors and Renderers

相关问题