「有沒有辦法讓窗戶在第1層關閉觸發第2層的動作?如果沒有,解決這個問題最好的辦法是什麼?
正如Boris the Spider指出的那樣,您應該使用模型對話框。你可能正在使用一個框架。您應該閱讀Modality以瞭解其行爲和功能。還需要一些時間來看看How to make Dialogs。簡而言之,打開對話模式(默認爲JOptionPane靜態showXxx
方法,並且可以在JDialog
上設置,通過setModalityType
或通過constructor),流程將「阻止」,直到對話框關閉。
下面是一個例子。對於這樣一個簡單的任務可能會過於複雜(因爲它可以很容易地通過JOptionPane
完成),但它顯示瞭如何使用JDialog
。看起來像ShowDialogActionListener
類。該對話框被設置爲可見,並且流動不會繼續在actionPerformed中,直到對話框關閉,這是從對話獲得Input
的時候。
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class DialogDemo {
private JFrame frame = new JFrame();
public DialogDemo() {
JButton button = new JButton("Open Dialog");
button.addActionListener(new ShowDialogActionListener());
frame.setLayout(new GridBagLayout());
frame.add(button);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class ShowDialogActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
InputDialog dialog = new InputDialog(frame, true);
System.out.println("Opened dialog.....");
long start = System.currentTimeMillis();
dialog.setVisible(true);
System.out.println("Dialog closed after "
+ (System.currentTimeMillis() - start) + " ms");
Input input = dialog.getInput();
ServiceOne service = new ServiceOne();
service.serviceMethod(input);
}
}
class ServiceOne {
public void serviceMethod(Input input) {
System.out.println(input.getInput());
}
}
class InputDialog extends JDialog {
private Input input;
public InputDialog(JFrame parent, boolean modal) {
super(parent, modal);
JPanel panel = new JPanel(new GridLayout(0, 1));
final JTextField field = new JTextField(20);
JButton okButton = new JButton("OK");
panel.add(field);
panel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = field.getText();
input = new Input();
input.setInput(text);
InputDialog.this.dispose();
}
});
setLayout(new GridBagLayout());
add(panel);
setSize(250, 250);
setLocationRelativeTo(parent);
}
public Input getInput() {
return input;
}
}
class Input {
private String input = "default";
public void setInput(String input) {
this.input = input;
}
public String getInput() {
return input;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DialogDemo();
}
});
}
}
正如我剛纔所說,同樣可以很容易地已與
String input = JOptionPane.showInputDialog("Enter a Message");
以上完成也將阻止流程執行。
你最有可能:1)運行關閉EDT的Swing組件,從而導致線程問題或2)不使用模態對話。 – 2014-08-30 16:47:52
我讀了線程,我認爲這可能是問題。我希望把事情分開,但我想我只需要把它放在一個班級。對於其他人而言,EDT是Event Dispatch Thread,這裏有一篇相當不錯的文章:http://stackoverflow.com/questions/7217013/java-event-dispatching-thread-explanation。 – Reggie 2014-09-03 23:21:00