gpt4 book ai didi

java - 从 JOptionPane 返回值

转载 作者:行者123 更新时间:2023-11-30 07:55:20 25 4
gpt4 key购买 nike

我制作了一个包含JPanelJOptionPane。该面板包含一个按钮和一个 Jtable。

JPanel p = atomicAttack.getPanel(); //make the panel and return it
JOptionPane.showOptionDialog(null, p,"Atomic Attacks",
JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,
null, new Object[]{}, null);

在 JButton 里面我有:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
selectedId=jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString();
}

我需要当用户点击按钮时,JOption 关闭selectedId 从 JOptionPane 返回

我看过this ,但这并不是我想要的。因为按钮没有为我返回值。

最佳答案

专注于模型,事情会变得更容易。

public static void main(String[] args) {
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("Selection", new Object[] { "A", "B", "C" });

JTable table = new JTable(tableModel);
ListSelectionModel selectionModel = table.getSelectionModel();

JPanel p = new JPanel(new BorderLayout());
p.add(table, BorderLayout.CENTER);

int option = JOptionPane.showConfirmDialog(null, p, "Atomic Attacks", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE);

if (JOptionPane.OK_OPTION == option) {
printSelection(selectionModel, tableModel);
} else {
selectionModel.clearSelection();
}

}

private static void printSelection(ListSelectionModel selectionModel, TableModel tableModel) {
for (int i = selectionModel.getMinSelectionIndex(); i <= selectionModel.getMaxSelectionIndex(); i++) {
if (selectionModel.isSelectedIndex(i)) {
Object selectedValue = tableModel.getValueAt(i, 0);
System.out.println(selectedValue);
}
}
}

如果你现在选择多行

Table model selection in JOptionPane

然后按确定按钮,结果将是

A
C

如果你想要一个单一的选择,你可以设置

ListSelectionModel selectionModel = table.getSelectionModel();      
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

关于java - 从 JOptionPane 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43292499/

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