我想在创建 JFrame 后关闭它。
(不带按钮)。
但是在构造函数上
没有。你没有。您不希望尝试显示一个 Swing GUI 对象,然后在它完全构建之前将其关闭。我认为你想做的是显示窗口,显示一个 JOptionPane,然后关闭 GUI 窗口。如果是这样,您希望在调用 GUI 对象的构造函数的代码中而不是在构造函数中执行此操作,以便您处理完全实现的对象。例如,像这样的:
ClientSideForm clientForm = new ClientSideForm();
clientForm.setVisible(true);
JOptionPane.showMessageDialog(rootPane, "Terjadi Kesalahan Dalam Membuka Aplikasi Utama",
"Kesalahan", JOptionPane.ERROR_MESSAGE);
clientForm.dispose();
旁注:
- 该按钮之所以有效,是因为即使它是在由 ClientSideForm 构造函数调用的方法中创建的,并且即使它的 ActionListener 可能已附加在代码的同一部分中,它也不会在构造函数中执行其操作,而是在之后执行,在完全创建并显示 ClientSideForm 对象后,按下按钮会激发其 ActionListener 的操作。
- 如果您的 GUI 有几个 JFrame 显示然后消失,请考虑修改对用户更友好的结构,因为大多数用户不希望向他们推送一堆窗口。请查看The Use of Multiple JFrames, Good/Bad Practice? 了解为什么这很重要并查看可用的替代方案。
- 如果您希望 GUI 显示一段时间,然后关闭,请为此使用 Swing Timer。
- 通过让您的类扩展 JFrame,您可能会将自己画在一个角落,迫使您创建和显示 JFrame,而通常需要更大的灵活性。事实上,我敢冒险说,我创建的大部分 Swing GUI 代码不扩展了 JFrame,事实上你很少愿意这样做这个。更常见的是,您的 GUI 类将用于创建 JPanel,然后可以将其放置到 JFrame 或 JDialogs 或 JTabbedPanes 中,或者在需要时通过 CardLayouts 交换。这将大大增加您的 GUI 编码的灵活性。
例如下面的代码会显示一个GUI,一半时间会显示JOptionPane错误信息,然后在错误信息关闭后关闭GUI,另一半时间会显示GUI 2 秒后自动关闭:
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
@SuppressWarnings("serial")
public class TestPanel extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = 400;
private static final int TIMER_DELAY = 2 * 1000; // 2 seconds
public TestPanel() {
JLabel label = new JLabel("Test GUI");
label.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 100));
setPreferredSize(new Dimension(PREF_W, PREF_H));
setLayout(new GridBagLayout());
add(label);
}
// this code is called from a main method, but could be called anywhere, from
// a JButton's action listener perhaps. If so, then I'd probably not create
// a new JFrame but rather a JDialog, and place my TestPanel within it
private static void createAndShowGui() {
TestPanel mainPanel = new TestPanel();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
if (Math.random() > 0.5) {
// 50% chance of this happening
String message = "Error In Opening Main App";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(frame, message, "Error", type);
frame.dispose();
} else {
// run timer
new Timer(TIMER_DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose(); // dispose gui when time's up
((Timer) e.getSource()).stop(); // and stop the timer
}
}).start();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}