我在處理多個框架時隱藏組件未正確放置時出現問題。當框架不可見時,Java不處理對話框
總之,我不能處置一個父母是隱藏框架的模式對話框。
例如:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class MultipleFrameTest {
public static void main(String[] args) {
TestFrame test = new TestFrame();
FrameTester tester = new FrameTester(test);
tester.setVisible(true);
}
private static class TestFrame extends JFrame {
JDialog dialog;
java.util.Timer timer;
public TestFrame() {
super("Test Frame");
this.dialog = null;
this.timer = new java.util.Timer("Frame Timer");
fillFrame();
pack();
}
private void fillFrame() {
JButton dialogButton = new JButton("Launch Model Dialog");
dialogButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JOptionPane pane = new JOptionPane("Wait for 2 seconds",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
dialog = pane.createDialog(TestFrame.this, "Question");
timer.schedule(new TimerTask() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestFrame.this.setVisible(false);
if (dialog != null) {
dialog.setVisible(false);
dialog.dispose();
dialog = null;
}
}
});
}
}, 2 * 1000);
dialog.setVisible(true);
}
});
JPanel panel = new JPanel();
panel.add(dialogButton);
add(panel);
}
}
private static class FrameTester extends JFrame {
JFrame frame;
public FrameTester(JFrame frame) {
super("Frame Tester");
this.frame = frame;
fillFrame();
pack();
}
private void fillFrame() {
JButton toggleButton = new JButton("Toggle Frame Visibility");
toggleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
frame.setVisible(!frame.isVisible());
}
});
JPanel panel = new JPanel();
panel.add(toggleButton);
add(panel);
}
}
}
要運行這個例子:
- 點擊 「切換幀可見性」 按鈕。這將顯示
TestFrame
。 - 點擊「Launch Modal Dialog」按鈕。這會彈出一個
JOptionPane
。 - 等待2秒鐘,
TimerTask
隱藏TestFrame
和dispose()
JOptionPane
。 - 單擊「切換框架可視性按鈕」。
TestFrame
將變爲可見,並且將看到JOptionPane
被附加。
我知道我可以通過配置JOptionPane
隱藏TestFrame
之前解決這個問題:
- TestFrame.this.setVisible(false);
if (dialog != null) {
dialog.setVisible(false);
dialog.dispose();
dialog = null;
}
+ TestFrame.this.setVisible(false);
有誰知道爲什麼發生這種情況?我期望模態對話框即使在處置時處於隱藏狀態也不會消失。
另請參見[*使用多個JFrames,好/壞實踐?*](http://stackoverflow.com/q/9554636/230513)。 – trashgod 2014-08-28 21:35:10