2012-05-23 49 views

回答

4

只需根據您的模型禁用單元格的編輯。在您的TableModel中,覆蓋/實現isCellEditable()方法以返回複選框的「值」。

雖然下面的例子不是基於JComboBox中,它說明了如何基於在該行開頭的複選框的值來禁用一個單元的版本:

import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.SwingUtilities; 
import javax.swing.table.DefaultTableModel; 

public class TestTable { 

    public JFrame f; 
    private JTable table; 

    public class TestTableModel extends DefaultTableModel { 

     public TestTableModel() { 
      super(new String[] { "Editable", "DATA" }, 3); 
      for (int i = 0; i < 3; i++) { 
       setValueAt(Boolean.TRUE, i, 0); 
       setValueAt(Double.valueOf(i), i, 1); 
      } 
     } 

     @Override 
     public boolean isCellEditable(int row, int column) { 
      if (column == 1) { 
       return (Boolean) getValueAt(row, 0); 
      } 
      return super.isCellEditable(row, column); 
     } 

     @Override 
     public Class<?> getColumnClass(int columnIndex) { 
      if (columnIndex == 0) { 
       return Boolean.class; 
      } else if (columnIndex == 1) { 
       return Double.class; 
      } 
      return super.getColumnClass(columnIndex); 
     } 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new TestTable().initUI(); 
      } 
     }); 
    } 

    protected void initUI() { 
     table = new JTable(new TestTableModel()); 
     f = new JFrame(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setSize(300, 300); 
     f.setLocationRelativeTo(null); 
     f.add(new JScrollPane(table)); 
     f.setVisible(true); 
    } 

} 
+0

+1使用該模型。 – trashgod

+0

@trashgod Thx編輯,我的英語遠非完美;-)乾杯 –

+0

但基於Swing知識的邏輯與離完美並不遙遠 – mKorbel