[英]JFrame not closing when it should
在制作JFrame時調用此代碼段,當它到達dispose()行時,它不會關閉。 我知道它正在進入那個塊,因為另一個JFrame確實打開了,唯一的問題是它沒有關閉。 誰知道為什么?
public LogIn(String title)
{
super(title);
checker = new Open("");
deserializeOpen();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
getContentPane().setLayout(new BorderLayout());
getContentPane().setBackground(Color.orange);
Login = new JButton("Login");
Create = new JButton("New Profile");
Login.addActionListener(this);
Create.addActionListener(this);
buttons = new JPanel();
buttons.setBackground(Color.orange);
buttons.setLayout(new GridLayout(0,2));
buttons.add(Login);
buttons.add(Create);
Title = new JLabel("Scrambler");
Title.setFont(new Font("Times New Roman", Font.BOLD, 24));
Name = new JTextField(4);
name = new JLabel("Name:");
password = new JPasswordField(4);
pass = new JLabel("Password:");
Text = new JPanel();
Text.setLayout(new GridLayout(6,0));
Text.setBackground(Color.orange);
Text.add(Title);
Text.add(name);
Text.add(Name);
Text.add(pass);
Text.add(password);
getContentPane().add(Text, BorderLayout.CENTER);
getContentPane().add(buttons, BorderLayout.SOUTH);
show();
}
public void deserializeOpen()
{
try
{
FileInputStream door = null;
try
{
door = new FileInputStream("Check.ser");
}
catch (FileNotFoundException e)
{
new Activator();
dispose();
}
if(door!=null)
{
ObjectInputStream reader = new ObjectInputStream(door);
checker = (Open) reader.readObject();
}
}
catch (IOException e){e.printStackTrace();}
catch (ClassNotFoundException e){e.printStackTrace();}
}
這些只是代碼的兩個部分,正文是第一部分,反序列化是導致問題的部分
我很確定到達dispose()行是因為我只是將一個System.out.print()放在dispose()的下方和下方,並且都打印出來
在你的JFrame子類的構造函數中,首先調用deserializeOpen()
,它釋放幀(沒有效果,因為它還沒有顯示),然后調用show()
來打開框架。 所以你可能打算開關 ,而是你的代碼關閉打開 。
順便說一句:自JDK1.5以來不推薦使用show()
方法,你應該使用setVisible(true)
代替。 我建議您在deserializeOpen()
傳播異常並將其捕獲到外部,這樣您就可以決定是否打開框架而不是打開和關閉框架:
public void deserializeOpen() throws Exception { ... }
在構造函數中:
try {
deserializeOpen();
setVisible(true);
} catch(Exception e) {
e.printStacktrace(); // or any other error handling
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.