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.
The problem is that you're creating a new
Boardobject insetUpBoardand adding that to your JFrame:So when you use
repaint(), you're repainting the instance ofBoardthat you created in themainmethod, and not the instance you created insetUpBoard, which is the one you add to the frame.This can be easily fixed by using
Board board = this;insetUpBoard, or, even simpler in my opinion, just usingframe.add(this). Subsequent calls torepaintwill then schedule a call topaintfor the same Board object that you created in the main method.Also, since you're working with Swing, don't use
paint, and instead usepaintComponent, making sure thatsuper.paintComponent(g)is the first statement in the method body.