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