我正在尝试制作一个Connect Four游戏来提高我使用Java Graphics和学校项目的能力。游戏的背景将是蓝色JPanel
,游戏板将是一个单独的JPanel,将放置在背景之上。请参阅下面的课程:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class gameBoard extends JPanel {
private Board bored;
public gameBoard(){
setLayout(new BorderLayout());
bored = new Board();//does not appear in Center Region of gameBoard
add(bored, BorderLayout.CENTER);
}
public void paint(Graphics g){//This line is the one that is acting weird.
//blue rectangle board is here, but when repaint called
//JFrame turns blue and does not add new JPanel called above
g.setColor(Color.BLUE);
g.fillRect(0, 0, 1456, 916);
}
}
和
import java.awt.BasicStroke;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class Board extends JPanel {
/*
* 2d array will represent board and take 1's(red) and 2's(black) the nums
* represent pieces, with each redraw of the board, a check will be done to
* compare a sum against blackWin and redWin. Sum will be created by
* summing a continuous line of 1's or 2's going left -> right
*/
public int[][] boardEvalMatrix = new int[6][7];
private final int blackWin = 8, redWin = 4;
public Board() {//1200 x 764
BoardMethods a = new BoardMethods();
a.printBoard(getBoard());
JPanel panelLORDY = new JPanel(new FlowLayout());
repaint();
}
public int[][] getBoard(){
return boardEvalMatrix;
}
public void paint(Graphics g){
g.setColor(Color.BLUE);//Drawing background with actual board as a Test
g.fillRect(0, 0, 1456, 916);//will not remain like this
Graphics2D newG = (Graphics2D) g;
newG.setStroke(new BasicStroke(15));
g.setColor(Color.YELLOW);
for(int a = 0; a < 6; a++)//rows for board --- rowHeight is 127
g.drawRect(128, 68+ (a*127), 1200, 127);
//g.setColor(Color.BLACK);
//newG.setStroke(new BasicStroke(8));
//for(int a = 0; a < 7; a++)//columns for board --- columnWidth is 171
// g.drawRect(208, 152, 70, 10);
//g.drawLine(50,0, 1456, 916); //width 1456 length 916 - school computer monitors
}
}
所发生的事情就是这样:
问题1:
当我在public void paint(Graphics g)
类中添加gameBoard
行时,即使没有调用{{{{}}},我运行驱动程序时显示的显示也只是灰色JFrame
1}}并且repaint()
方法为空。但是,当我删除创建paint()
方法的行时,问题就消失了,并且出现了正确的显示。
问题2:
即使我放置代码在paint
类的paint
方法中绘制蓝色矩形并调用gameBoard
,repaint()
也是蓝色,这部分是正确的。我知道Java从上到下执行命令所以我确保在绘制蓝色矩形之后将实际游戏板添加到JFrame
gameBoard
的代码,但它没有用。
问题:
我做错了什么以及如何解决?
答案 0 :(得分:1)
要更改您刚才使用的面板的背景颜色:
setBackground( Color.BLUE );
面板上的。然后就不需要自定义绘画了。
当你覆盖paint()
并忘记super.paint()
时,你真的搞砸了绘画过程。 paint()
方法负责在面板上绘制子组件。由于你没有调用super.paint()
,所以孩子们永远不会被画画。
如果由于某种原因确实需要自定义绘画,那么您应该覆盖paintComponent()
方法,并且不要忘记调用super.paintComponent()
。不要覆盖paint()。
阅读关于“自定义绘画”的Swing教程,尤其是A Closer Look at the Paint Mechanism部分,了解更多信息和示例。