我在这里遇到无法解释的代码问题。我有两个Jframes
,第一个有一个按钮,单击该按钮会转到第二个框架。这很好。但是这里有一个问题:第二帧首先显示为skeleton
,而没有添加我的JComponents
。它正在等待所有语句执行完毕,直到paints
在JComponents
上的JFrame
显示skeleton
为止。
为什么会这样?在执行下一行代码之前,如何使它“完全显示/绘制”所有组件?
下面是我的代码
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* @author JWizard
*/
public class Test {
private JFrame frame;
private JButton button;
public Test() {
initGUI();
button.addActionListener((ActionEvent e) -> {
JFrame frame1 = new JFrame("Second Jframe");
frame1.setPreferredSize(new Dimension(300, 300));
frame1.getContentPane().add(new JLabel("Swing Component"));
frame1.pack();
frame1.setVisible(true);
frame1.setLocationRelativeTo(null);
/**
* After executing the above line,
* 'frame1.setLocationRelativeTo(null);', I am expecting the program
* to have fully "painted" my fame1 GUI, showing the label.
*/
try {
Thread.sleep(7000);
System.out.println("statement 1");
Thread.sleep(7000);
System.out.println("statement 2");//after executing this statment thats when
//the program paints the components of frame1
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
private void initGUI() {
frame = new JFrame("Frame 1");
button = new JButton("Go to Frame 2");
frame.setLayout(new FlowLayout(FlowLayout.LEADING));
frame.setPreferredSize(new Dimension(300, 300));
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args) {
Test text = new Test();
}
}
最佳答案
试试看:
public Test() {
initGUI();
button.addActionListener((ActionEvent e) -> {
JFrame frame1 = new JFrame("Second Jframe");
frame1.setPreferredSize(new Dimension(300, 300));
frame1.getContentPane().add(new JLabel("Swing Component"));
frame1.pack();
frame1.setVisible(true);
frame1.setLocationRelativeTo(null);
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
try {
Thread.sleep(7000);
System.out.println("statement 1");
Thread.sleep(7000);
System.out.println("statement 2");
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}.execute();
});
}