1
我正在創建一個應用程序,該應用程序會創建大量帶有不同背景色的JFrame。起初他們是正確的顏色(黑色和紅色),但所有新的都保持白色。JFrame背景顏色無法正確更改
import java.awt.Color;
import java.util.Random;
import javax.swing.JFrame;
public class JFrameCrash{
private Random r;
private int screenHeight;
private int screenWidth;
private static final int FRAME_HEIGHT = 100;
private static final int FRAME_WIDTH = 200;
//private static final Color[] COLORS = {Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW, Color.BLACK, Color.WHITE, Color.GRAY, Color.CYAN, Color.PINK, Color.MAGENTA, Color.ORANGE};
private static final Color[] COLORS = {Color.RED, Color.BLACK};
public static void main(String[] args){
new JFrameCrash();
}
public JFrameCrash(){
screenHeight = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
screenWidth = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
r = new Random();
loop();
}
public JFrameCrash(int height, int width, Random rand){
this.screenHeight = height;
this.screenWidth = width;
r = rand;
run();
}
private void loop(){
while (true){
new JFrameCrash(screenHeight, screenWidth, r);
}
}
private void constructFrame(){
JFrame frame = new JFrame();
frame.setTitle("");
frame.setLocation(r.nextInt(screenWidth), r.nextInt(screenHeight));
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.getContentPane().setBackground(COLORS[r.nextInt(COLORS.length)]);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}
}
檢查CPU使用率 - 可能你的系統是太忙了,所有的油漆() - 因此你成功墜毀。 – Java42
所以你不認爲有什麼我可以做代碼明智的解決它? – Kryptos
您正在使用swing,請閱讀其中的API:Swing的線程策略 一般來說,Swing不是線程安全的。除非另有說明,否則必須在事件派發線程上訪問所有Swing組件和相關類。 –