2012-08-14 20 views
1

我正在尝试编写一些代码,允许用户通过单击JTable中的布尔单元格来填写文本字段。当使用JOptionPane时,JTable布尔值不会更新

image

我可以得到程序从表中的数据输入到一个文本字段,但我现在这样做的方法涉及的JOptionPane这对于一些奇怪的原因,从改变复选框停止表值(即复选框不会从黑色变为勾号)。不仅如此,而且选择不会更新,因此即使选择将其切换为true,最后一列中的值仍然为false。

我认为这可能与JOptionPane在某种程度上覆盖了选择事件有关,但我不太了解JOptionPane对象说的如何。我的代码是:

table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); 
ListSelectionModel selectionModel = table.getSelectionModel(); 
selectionModel.addListSelectionListener(new ListSelectionListener() { 

    public void valueChanged(ListSelectionEvent e) { 
     ListSelectionModel lsm = (ListSelectionModel) e.getSource(); 
     if (lsm.isSelectionEmpty()) { 
      //no rows are selected do nothing 
     } else { 
      //First find the row clicked 
      int selectedRow = lsm.getLeadSelectionIndex(); 
      /* 
       * put a popup here to ask the user which peak to associate 
       * the energy with. 
       */ 
      System.out.println(selectedRow); 
      //Get user to associate with a peak 
      availablePeaks = getAvailablePeaks(); 
      String returnVal = (String) JOptionPane.showInputDialog(
       null, 
       "Select the peak:", 
       "Peak Matching", 
       JOptionPane.QUESTION_MESSAGE, 
       null, 
       availablePeaks, null); 
      System.out.println(returnVal); 
      //Determine the selection 
      int index = 0; 
      for (int i = 0; i < availablePeaks.length; i++) { 
       if (availablePeaks[i] == returnVal) { 
        index = i; 
       } else { 
       } 
      } 
      //Set the peak value in the peak specifier to the energy in the row 
      double energy = (Double) table.getValueAt(selectedRow, 0); 
      System.out.println(energy); 
      frame.getPeakSetter().getPeakSpecifiers()[index].setEnergy(energy); 
      frame.getPeakSetter().getPeakSpecifiers()[index].getTextField().setText("" + energy); 
     } 
    } 
}); 

有谁知道为什么在ListSelectionListener一个JOptionPane会从更新的复选框阻表?

谢谢!

回答

2

我假设你的模型为isCellEditable()返回truegetColumnClass()返回Boolean.classJCheckBox列。这将启用默认修改者/编辑器,列出here

它看起来像选择行的手势正在调出对话框。目前还不清楚这是如何防止DefaultCellEditor结束;这个对我有用。由于您没有检查getValueIsAdjusting(),我很惊讶你没有看到两个ListSelectionEvent实例。

在任何情况下,每次选择更改时都会显示对话框,这似乎很麻烦。几个备选方案是可能的:

  • 保持ListSelectionListener,使细胞不可编辑从isCellEditable()返回false,并在模型中设置它的价值只有在对话圆满结束。

  • 下降,取而代之的是JButton编辑器的ListSelectionListenerhere所示。

  • 删除ListSelectionListener以支持自定义CellEditor,如下所述。

    table.setDefaultEditor(Boolean.class, new DefaultCellEditor(new JCheckBox()) { 
    
        @Override 
        public boolean stopCellEditing() { 
         String value = JOptionPane.showInputDialog(...); 
         ... 
         return super.stopCellEditing(); 
        } 
    }); 
    
+0

谢谢!我决定保留ListSelectionListener并使最后一列中的单元格不可编辑。如果用户单击单元格并且选择使表格现在正确更新。 :) – user1353285 2012-08-15 09:30:35