2012-08-14 19 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