添加JComponent时,java图形中的paint函数是否被多次调用? [英] Is the paint function in java graphics called multiple times when I add a JComponent?
问题描述
我正在制作一个国际象棋游戏,其中每个图块(类)都有一个 X 和 Y 位置,棋盘由二维图块阵列表示.我有一个名为 board 的类,它扩展了 JComponent,我的主函数将板添加到 JFrame.根据我所阅读的内容,paint 函数被隐式调用(不确定).问题是,当我尝试打印瓷砖的 x 和 y 位置(被迭代)时,它会打印所有 x 和 y 位置三遍,这让我相信油漆被调用了不止一次.
I am making a chess game in which each tile(class) holds an X and Y position and the board is represented by a two dimensional array of tiles. I have a class called board which extends JComponent and my main function adds the board to a JFrame. Based on what I have read, the paint function is called implicitly(not sure). The problem is that when i tried printing the x and y position of the tiles(being iterated over) it prints all of the x and y positions three times, which led me to believe that paint is being called more than once.
板类:
class Board extends JComponent{
Tile[][] board1;
Board(Pieces p,boolean containPiece){
//initialize board
board1 = board; // set attribute
}
public void paint(Graphics g){
for(int i = 0; i < board1.length; i++){
for(int j = 0; j < board1.length; j++){
g.fillRect(board1[j][i].xPosition+130, board1[j][i].yPosition+20,board1[j][i].tileWidth,board1[j][i].tileHeight);
System.out.println(j+ " "+ " " + i );
if((j+i)%2 == 0){
g.setColor(Color.BLACK);
}
else{
g.setColor(Color.WHITE);
}
}
}
}
}
主类:
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(350,10,700, 600);
Knight k = new Knight("Knight","K","white",4,5,3);
frame.getContentPane().add(new Board(k,true));
frame.setVisible(true);
}
输出如下(与代码格式不同但内容相同)但重复了两次:
the output is the following(not in same format as code but same content) but repeated twice more:
0 0, 1 0, 2 0, 3 0, 4 0, 5 0, 6 0, 7 0,
0 1 ,1 1 ,2 1 ,3 1 ,4 1 ,5 1 ,6 1 ,7 1,
0 2 ,1 2 ,2 2 ,3 2 ,4 2 ,5 2 ,6 2 ,7 2 ,
0 3 ,1 3 ,2 3 ,3 3 ,4 3 ,5 3 ,6 3 ,7 3 ,
0 4 ,1 4 ,2 4 ,3 4 ,4 4 ,5 4 ,6 4 ,7 4,
0 5 ,1 5 ,2 5 ,3 5 ,4 5 ,5 5 ,6 5 ,7 5 ,
0 6 ,1 6 ,2 6 ,3 6 ,4 6 ,5 6 ,6 6 ,7 6 ,
0 7 ,1 7 ,2 7 ,3 7 ,4 7 ,5 7 ,6 7 ,7 7
推荐答案
在系统触发的绘制操作中,系统请求组件渲染其内容,通常是出于以下原因之一:
In a system-triggered painting operation, the system requests a component to render its contents, usually for one of the following reasons:
- 组件首先在屏幕上可见.
- 组件已调整大小.
- 组件有损坏需要修复.(例如,之前遮挡组件的东西已经移动,并且组件之前被遮挡的部分已经暴露).
这篇关于添加JComponent时,java图形中的paint函数是否被多次调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!