0
我在这里遇到了我的代码问题,我无法解释。我有两个Jframes
,第一个有一个按钮,点击它时会导致第二帧。这工作正常。但是有一个问题在这里:第一帧出现为skeleton
,没有添加JComponents
。它正在等待,直到所有的语句都被执行,即paints
的JComponents
的JFrame
显示为skeleton
。为什么Swing在这里推迟'全面绘制'JFrame?
这是为什么?我怎样才能在执行下一行代码之前“完全显示/绘制”所有组件?
下面是我的代码
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();
}
}
您阻止事件调度线程用来处理用户界面等的重新粉刷 – Thomas
@Thomas我在哪里阻止它? – JWizard
“我在哪里阻止它?” 'Thread.sleep(7000);'这里。 – Fildor