基本的に JFrame のガラス枠として設定された JPanel である独自のダイアログを作成しています。ダイアログが表示されている間は setVisible() の後のすべてのコードが実行されず、ダイアログが閉じられると setVisible() の後の残りのコードを続行する必要があるという意味で、ダイアログをモーダルにしたいと考えています。
これを実現するために、スレッドを使用してダイアログを表示しています。別のスレッドで実行されるため、SwingUtilities.invokeLater() メソッドを使用して GUI を更新する必要があることはわかっています。ただし、私のダイアログは画面に表示されません。
これが私のコード例です:
final JFrame frame = new JFrame();
frame.setBounds(0, 0, 1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton button = new JButton("Text");
button.setBounds(200, 300, 110, 50);
button.addActionListener(new ActionListener() {
boolean dispose;
public void actionPerformed(ActionEvent e) {
try {
Thread thread = new Thread(new Runnable() {
public void run() {
final JPanel panelGlass = new JPanel(null);
panelGlass.setBounds(frame.getBounds());
panelGlass.setBackground(Color.red);
frame.setGlassPane(panelGlass);
JButton btnClose = new JButton("close");
btnClose.setBounds(100, 100, 110, 50);
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose = true;
}
});
panelGlass.add(btnClose);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
dispose = false;
panelGlass.setVisible(true);
}
});
while (!dispose) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
panelGlass.setVisible(false);
}
});
thread.start();
thread.join();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
frame.getContentPane().add(button);
frame.setVisible(true);
ダイアログが表示されないのはなぜですか?