[英]repaint in java not working
I am trying to draw a rectangle which its position is updated every second, for that I have a class which extends JPanel and in it I have overriden the paint ( or paintComponent) function_ I have tried both _ but apparanetly this function is called only once and as it is shown in the code below when I try to call it in an infinite loop with repaint function it doesnt get called, any ideas what I can do? 我正在尝试绘制一个矩形,该矩形的位置每秒更新一次,因为我有一个扩展JPanel的类,并且在其中重写了paint(或paintComponent)函数_我已经尝试了_,但是类似地,此函数仅被调用一次正如下面的代码所示,当我尝试使用重画功能在无限循环中调用它时,它没有被调用,我能做什么吗?
public class Board extends JPanel implements KeyListener{
public void setUpBoard(){
JFrame frame = new JFrame();
Board board = new Board();
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLocation(350, 80);
frame.add(board);
}
public void paint(Graphics g){
g.setColor(Color.RED);
g.fillRect(food.getX(),200,20,20);
}
}
the code above is the graphic part, below is the main function, which is placed in another class : 上面的代码是图形部分,下面的是主要功能,位于另一个类中:
public static void main(String[] args) throws InterruptedException {
Board board = new Board();
FoodGenerator food = new FoodGenerator();
board.setUpBoard();
while(true){
board.repaint();
food.adder();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
in the code above food.adder is where the position of the rectangle is updated, which I have checked and doesnt have any issues. 在food.adder上面的代码中,矩形的位置已更新,我已经检查过了,没有任何问题。
The problem is that you're creating a new Board
object in setUpBoard
and adding that to your JFrame: 问题是,你正在创建一个新的
Board
在对象setUpBoard
并补充说,到你的JFrame:
Board board = new Board();
// ...
frame.add(board);
So when you use repaint()
, you're repainting the instance of Board
that you created in the main
method, and not the instance you created in setUpBoard
, which is the one you add to the frame. 因此,当您使用
repaint()
,您将重新绘制您在main
方法中创建的Board
实例,而不是您在setUpBoard
创建的实例(添加到框架中)。
This can be easily fixed by using Board board = this;
这可以通过使用
Board board = this;
轻松解决Board board = this;
in setUpBoard
, or, even simpler in my opinion, just using frame.add(this)
. 在
setUpBoard
,或者,我认为更简单,仅使用frame.add(this)
。 Subsequent calls to repaint
will then schedule a call to paint
for the same Board object that you created in the main method. 然后,随后的
repaint
调用将为您在main方法中创建的同一Board对象安排一次paint
调用。
Also, since you're working with Swing, don't use paint
, and instead use paintComponent
, making sure that super.paintComponent(g)
is the first statement in the method body. 另外,由于您正在使用Swing,因此请不要使用
paint
,而要使用paintComponent
,请确保super.paintComponent(g)
是方法主体中的第一条语句。
另一个问题是,重新绘制调用是在主线程上完成的,而不是在事件线程上进行的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.