repaint in java not working

661 views Asked by At

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?

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.

2

There are 2 answers

1
TNT On

The problem is that you're creating a new Board object in setUpBoard and adding that to your 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.

This can be easily fixed by using Board board = this; in setUpBoard, or, even simpler in my opinion, just using 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.

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.

0
FredK On

Another problem is that the repaint calls are being done on the main thread, not on the event thread.