Java 使用JOptionPane时不更新JTable布尔值
我试图编写一些代码,允许用户通过单击JTable中的布尔单元格来填充文本字段 我可以让程序将表格中的数据输入到文本字段中,但我目前的方法是使用JOptionPane,出于某种奇怪的原因,它会阻止表格更改复选框值,即复选框不会从黑色变为勾选。不仅如此,所选内容也不会更新,因此最后一列中的值仍然为false,即使所选内容应将其切换为true 我认为这可能与JOptionPane以某种方式覆盖选择事件有关,但我对JOptionPane对象了解不够,无法说明如何覆盖选择事件。我的代码是:Java 使用JOptionPane时不更新JTable布尔值,java,swing,jtable,joptionpane,Java,Swing,Jtable,Joptionpane,我试图编写一些代码,允许用户通过单击JTable中的布尔单元格来填充文本字段 我可以让程序将表格中的数据输入到文本字段中,但我目前的方法是使用JOptionPane,出于某种奇怪的原因,它会阻止表格更改复选框值,即复选框不会从黑色变为勾选。不仅如此,所选内容也不会更新,因此最后一列中的值仍然为false,即使所选内容应将其切换为true 我认为这可能与JOptionPane以某种方式覆盖选择事件有关,但我对JOptionPane对象了解不够,无法说明如何覆盖选择事件。我的代码是: table.s
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为什么会阻止表更新复选框吗
谢谢 我假设您的模型为isCellEditable返回true,为JCheckBox列返回Boolean.class。这将启用列出的默认编校器/编辑器 看起来,选择行的手势会打开对话框。目前还不清楚这是如何阻止DefaultCellEditor得出结论的;它对我有用。由于您没有检查getValueIsAdjusting,我很惊讶您没有看到两个ListSelectionEvent实例 在任何情况下,每次选择更改时打开对话框似乎都很麻烦。有几种备选方案: 保持ListSelectionListener,通过从isCellEditable返回false使单元格不可编辑,并仅在对话框成功结束时在模型中设置其值 删除ListSelectionListener,使用JButton编辑器,如图所示 删除ListSelectionListener,使用自定义CellEditor,如下所述
table.setDefaultEditor(Boolean.class, new DefaultCellEditor(new JCheckBox()) {
@Override
public boolean stopCellEditing() {
String value = JOptionPane.showInputDialog(...);
...
return super.stopCellEditing();
}
});
谢谢我决定保留ListSelectionListener,并使最后一列中的单元格不可编辑。如果用户单击单元格并做出选择,则表格现在将正确更新: