我想在创建后关闭JFrame。
(不是按钮)。
但在构造函数
上public class ClientSideForm extends javax.swing.JFrame {
LocalInformation li = new LocalInformation();
ClientSetting cs = new ClientSetting();
public ClientSideForm() throws UnknownHostException {
initComponents();
setLocalInfo();
setDefault();
try {
if (!StartApp()) {
JOptionPane.showMessageDialog(rootPane, "Terjadi Kesalahan Dalam Membuka Aplikasi Utama", "Kesalahan", JOptionPane.ERROR_MESSAGE);
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
this.dispose();
}
}
如果我在按钮上实现它可以很好地工作
但是我想在创建它之后关闭这个JFrame。
由于
答案 0 :(得分:2)
创建后我想关闭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();
附注:
例如,下面的代码将显示一个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());
}
}