[英]Java setBackground() confusion
我是Java swing庫的新手,我目前在設置JFrame的背景時遇到了一些麻煩。
我已經閱讀了jframe-setbackground-not-working-why和它里面的鏈接,但它似乎不適合這里。
這是我的代碼:
public class Board extends JPanel{
public enum pointType{
EMPTY,
CARRIER,
BALL;
}
private class Point{
int x;
int y;
pointType type;
public void paint (Graphics2D g2){
// color changes depends on pointType
g2.setColor(Color.WHITE);
g2.fillOval(x,y,25,25);
}
}
Point[][] myBoard;
public Board(){
//constructor, myBoard = 2d List of points
}
//.. other methods and class variables
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
for(int k =HEIGHT; k>=0; k--){
for(int i=WIDTH; i>=0; i--){
// call paint method for each points on board
myBoard[i][k].print(g2);
}
}
}
public static void main(String[] args){
Board board = new Board();
JFrame myFrame = new Jframe("Game");
myFrame.add(board);
board.setBackground(Color.YELLOW);
myFrame.setVisible(true);
mtFrane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
我的代碼根據其pointType成功打印所有點,但未正確設置電路板顏色(仍為默認背景)。
所以這里是問題:
1)我應該如何正確設置背景?
2)我覺得我的代碼沒有正確使用JPanels / JFrames / Graphics,如果是這樣的話,有關如何改進代碼結構的任何建議嗎?
使用paintComponent()
而不是paint()
public class Board extends JPanel{
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
...
}
}
欲了解更多信息,請查看以下帖子:
默認paintComponent()
在方法JPanel
使用存儲在背景顏色JPanel
的實例變量; 但是,重寫的paintComponent()
方法不會使用實例變量,因此使用setBackground()
更改它將不會執行任何操作。
如果你想堅持重寫paintComponent()
方法,你應該畫一個框填充的整個區域JPanel
與你想要的內部顏色paintComponent()
方法。
Board
的新paintComponent()
方法如下所示:
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.YELLOW);
g2.fillRect(0, 0, getWidth(), getHeight()); // Fill in background
// Do everything else
for(int k =HEIGHT; k>=0; k--){
for(int i=WIDTH; i>=0; i--){
// call paint method for each points on board
myBoard[i][k].print(g2);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.