Return 来自 JOptionPane 的值

Return the value from JOptionPane

我制作了一个 JOptionPane,其中包含一个 JPanel。该面板包含一个按钮和一个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 get return JOptionPane?

我看过 this,但这不是我要找的。 因为这个按钮对我来说return没有价值。

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

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);
        }
    }
}

如果你现在 select 多行

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

A
C

如果你想要单个 selection 你可以设置

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