0

When i use Timer and TimerTask to have it run the code every second it doesn't draw to the JFrame but still runs the code.

public void drawObject(Graphics g, int scale){
        g.setColor(colors[rand]);
        g.fillOval(xPos,yPos,scale*size,scale*size);
    }
    public void paint(Graphics g) {
        setBackground(Color.WHITE);

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            boolean ting = false;
            public void run() {
                if(ting){
                    g.setColor(Color.white);
                    g.fillRect(0, 0, getWidth(), getHeight());
                }
                for(int i=0;i<jTP.physicsObjectArrayList.size();i++){
                    jTP.physicsObjectArrayList.get(i).drawObject(g,scale);
                    System.out.println("test");
                }
                for(int i=0;i<jTP.physicsObjectArrayList.size();i++) {
                    jTP.physicsObjectArrayList.get(i).setxPos(jTP.physicsObjectArrayList.get(i).getxPos()+getForceX(i)+getVelocityX(i));
                    jTP.physicsObjectArrayList.get(i).setyPos(jTP.physicsObjectArrayList.get(i).getyPos()+getForceY(i)+getVelocityY(i)+getGravity(i));
                }
                ting = true;
            }
        };

        timer.scheduleAtFixedRate(task, new Date(System.currentTimeMillis()), (long) 1000.0);

I am expecting it to draw the circle but it doesn't but it does print test to the command line. when i comment out the timer stuff it does draw the circle but then it doesn't have the delays

  • 3
    Use a Swing `Timer` instead of `java.util.Timer`. Don't start timer in `paint` - in fact, don't override `paint` and don't paint directly to the frame, use a `JPanel` instead - see [Performing Custom Painting](https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) and [How to Use Swing Timers](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html) - for [example](https://stackoverflow.com/questions/23443503/changing-background-color-on-every-clock-tick/23443563#23443563) – MadProgrammer May 22 '23 at 00:33
  • 3
    A painting method is for painting only. Don't have Timer logic in the painting method. Painting is done by using the Graphics object passed to the paintComponent() method of a JPanel. See: https://stackoverflow.com/a/54028681/131872 for an example of using a Swing Timer for animation. – camickr May 22 '23 at 00:35
  • For additional code context, you can view the full file on my github [link](https://github.com/boxtop312/comp-sci-IntelliJ-IDEA/blob/main/src/Physics_Final.java) – alex miranda May 22 '23 at 01:40

0 Answers0