gpt4 book ai didi

java - 使用 JOptionPane 时 JTable boolean 值不更新

转载 作者:行者123 更新时间:2023-11-30 04:42:25 24 4
gpt4 key购买 nike

我正在尝试编写一些代码,允许用户通过单击 JTable 中的 boolean 单元格来填写文本字段。

image

我可以让程序将表中的数据输入到文本字段中,但我当前执行此操作的方法涉及 JOptionPane,由于某种奇怪的原因,它阻止表更改复选框值(即复选框值)框不会从黑色变为打勾)。不仅如此,选择也不会更新,因此最后一列中的值仍然为 false,即使选择应将其切换为 true。

我认为这可能与 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 会阻止表格更新复选框吗?

谢谢!

最佳答案

我假设您的模型为 isCellEditable() 返回 true 并且 getColumnClass() 返回 Boolean.class > 对于 JCheckBox 列。这将启用默认的 rednerer/编辑器,列出 here .

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

无论如何,每次选择更改时都弹出一个对话框似乎很麻烦。有几种可能的替代方案:

  • 保留 ListSelectionListener,通过从 isCellEditable() 返回 false 使单元格不可编辑,并将其值设置为仅当对话成功结束时才使用模型。

  • 放弃 ListSelectionListener 以支持 JButton 编辑器,如图 here .

  • 删除 ListSelectionListener,转而使用自定义 CellEditor,如下所述。

    table.setDefaultEditor(Boolean.class, new DefaultCellEditor(new JCheckBox()) {

    @Override
    public boolean stopCellEditing() {
    String value = JOptionPane.showInputDialog(...);
    ...
    return super.stopCellEditing();
    }
    });

关于java - 使用 JOptionPane 时 JTable boolean 值不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11955169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com