[英]JOptionpane + JDialog (non-modal) get the return value
我有一個帶有兩個輸入文本字段的非模態對話框,其中顯示了帶有OK和CANCEL按鈕的JOptionPane。 我將顯示如下對話框。
JTextField field_1 = new JTextField("Field 1");
JTextField field_2 = new JTextField("Field 2");
Object[] inputField = new Object[] { "Input 1", field_1,
"Input_2", field_2 };
JOptionPane optionPane = new JOptionPane(inputField,
JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = optionPane.createDialog(null, "Input Dialog");
dialog.setModal(false);
dialog.setVisible(true);
如何從對話框中獲取返回值? 意味着我需要獲得是否按下確定或取消按鈕。 怎么能實現這個?
使用getValue()將告訴您對話框是如何關閉的。 由於它是非模態的,因此一旦對話框關閉,您需要獲取該信息,可能使用等待對話框關閉的Thread
來返回信息。 您沒有提供有關該信息需求的任何詳細信息,因此使用其他Thread
可能不是最適合您的解決方案。
一種方法是將ComponentListener
添加到dialog
並監聽其可見性以進行更改,
dialog.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) { }
@Override
public void componentMoved(ComponentEvent e) { }
@Override
public void componentShown(ComponentEvent e) { }
@Override
public void componentHidden(ComponentEvent e) {
if ((int) optionPane.getValue()
== JOptionPane.YES_OPTION) {
// do YES stuff...
} else if ((int) optionPane.getValue()
== JOptionPane.CANCEL_OPTION) {
// do CANCEL stuff...
} else {
throw new IllegalStateException(
"Unexpected Option");
}
}
});
注意:您應該使用ComponentAdapter
; 我正在展示整個界面以供說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.