我正在嘗試使用Java Graphics進行人生模擬遊戲,但是當運行我的代碼時,屏幕的左邊三分之一是灰色的。我希望整個屏幕都是白色的黑色方塊代表生活廣場。我對所有的java容器/面板和框架感到困惑。Java面板/幀圖形不能正常工作
這裏是我的代碼:
public class ConwayGame {
static JPanel panel;
static JFrame frame;
public static void main(String[] args) throws InterruptedException{
int [][] array = new int [40][40];
/*
* Set the pattern for Conway's Game of Life by manipulating the array below.
*/
/*Acorn
*/
array[19][15]=1;
array[19][16]=1;
array[19][19]=1;
array[19][20]=1;
array[19][21]=1;
array[18][18]=1;
array[17][16]=1;
panel = new JPanel();
Dimension dim = new Dimension(400, 400);
panel.setPreferredSize(dim);
frame = new JFrame();
frame.setSize(400,400);
Container contentPane = frame.getContentPane();
contentPane.add(panel);
frame.setVisible(true);
/*
* Runs the Game of Life simulation "a" number of times.
*/
Graphics g = panel.getGraphics();
drawArray(array, g);
//paint(g);
//Thread.sleep(125);
//g.dispose();
}
/*
* Creates the graphic for Conway's game of life.
*/
public static void drawArray(int[][] array, Graphics g) {
int BOX_DIM = 10;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
g.drawRect(i * BOX_DIM, j * BOX_DIM, 10, 10);
if (array[i][j] == 0) {
g.setColor(Color.WHITE);
g.fillRect(i * BOX_DIM, j * BOX_DIM, 10, 10);
}
if (array[i][j] == 1) {
g.setColor(Color.BLACK);
g.fillRect(i * BOX_DIM, j * BOX_DIM, 10, 10);
}
}
}
}
}
這裏是產生什麼樣的圖片:
不要使用'Graphics g = panel.getGraphics();'EVER。這不是定製繪畫在Swing中的工作原理。看看[在AWT和Swing中繪畫](http://www.oracle.com/technetwork/java/painting-140037.html)和[執行自定義繪畫](http://docs.oracle.com/javase/tutorial/uiswing/painting /)獲取關於繪畫如何工作的更多細節 – MadProgrammer