从JOptionPane返回值

时间:2017-04-08 09:44:44

标签: java swing 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 从JOptionPane返回

我见过this,但这并不是我想要的。 因为该按钮不会为我返回值。

1 个答案:

答案 0 :(得分:3)

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

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