我正在尝试制作一个四子棋游戏来提高我的 Java 图形能力并作为一个学校项目。游戏的背景将是蓝色的 JPanel
,游戏板将是一个单独的 JPanel,放置在背景之上。请参阅下面我的类(class):
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:
当我在 gameBoard
类中包含 public void Paint(Graphics g)
行时,运行驱动程序时出现的显示只是灰色的 JFrame
,即使没有调用 repaint()
并且 paint()
方法为空。但是,当我删除创建 paint
方法的行时,问题消失并出现正确的显示。
问题 2:
即使我将绘制蓝色矩形的代码放在 gameBoard
类的 paint
方法中并调用 repaint()
,JFrame
是蓝色的,这部分是正确的。我知道 Java 从上到下执行命令,所以我确保将实际游戏板添加到 gameBoard
JPanel
的代码是在绘制蓝色矩形之后出现的,但它没有工作。
问题:
我做错了什么以及如何解决它?
最佳答案
要更改您刚刚使用的面板的背景颜色:
setBackground( Color.BLUE );
在面板上。那么就不需要定制绘画了。
当你覆盖 paint()
并忘记 super.paint()
时,你就真的搞乱了绘画过程。 paint()
方法负责在面板上绘制子组件。由于您不调用 super.paint() ,因此子级永远不会被绘制。
如果由于某种原因您确实需要自定义绘制,那么您应该重写 paintComponent()
方法,并且不要忘记调用 super.paintComponent()
。不要重写paint()。
阅读有关“自定义绘画”的 Swing 教程,尤其是 A Closer Look at the Paint Mechanism 部分。了解更多信息和示例。
关于java - 图形代码的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30559848/