当用户在一个JFrame frame
中点击“关闭”时,我希望在程序退出前显示JFrame credits
显示我的姓名和内容2.5秒。现在,credits
正在显示,但没有textArea
和Button
的情况下是空的 - 无法找到错误的内容。
继承我的代码:
对于frame
frame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
int result = JOptionPane.showConfirmDialog(null, "Sind Sie sicher?", "Schließen", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION){
credits.setVisible(true);
try {
Thread.sleep(2500);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.exit(0);
} else {
//do nothing
}
}
});
对于credits
(只是初始化框架的类):
public class CreditsFrame extends JFrame {
Positioner pos = new Positioner();
private JPanel contentPane;
ImageIcon frameIcon = new ImageIcon("files/images/frameicon.png");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CreditsFrame frame = new CreditsFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CreditsFrame() {
setIconImage(frameIcon.getImage());
setAlwaysOnTop(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(pos.posX(pos.screenX, 441), pos.posY(pos.screenY, 210), 441, 210);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JTextArea txtarea = new JTextArea();
txtarea.setBounds(10, 11, 415, 125);
txtarea.setEditable(false);
txtarea.setBackground(Color.WHITE);
txtarea.setWrapStyleWord(true);
txtarea.setLineWrap(true);
txtarea.append("created by & more here");
contentPane.setLayout(null);
contentPane.add(txtarea);
JButton btnOk = new JButton("Ok");
btnOk.setBounds(154, 147, 89, 23);
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
contentPane.add(btnOk);
}
}
有关快速修复的建议吗?感谢。
答案 0 :(得分:2)
有关快速修复的建议吗?
是的,除非您想让整个GUI进入休眠状态,否则不要在Swing事件线程上调用Thread.sleep(...)
。而是使用Swing Timer来处理延迟。基本上,计时器的ActionListener将在毫秒延迟过后被调用。
如,
frame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
int result = JOptionPane.showConfirmDialog(null, "Sind Sie sicher?", "Schließen", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION){
credits.setVisible(true);
new Timer(2500, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit();
}
}).start();
} else {
//do nothing
}
}
});
另外,请查看The Use of Multiple JFrames, Good/Bad Practice?
将来会引起你的其他问题: