1

I'm trying to make the integer near "time left" to decrements by one and repaint every second but I can only see the changes when I resize the window constantly. I've tried this in Jcreator 3 in windows and in Ububtu 11.10 command line but it still doesn't work.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import javax.imageio.*;

class StatusPanel extends JPanel implements ActionListener {

    int time = 60;
    int round = 1;
    Timer timer;

    public StatusPanel() {
        this.timer = new Timer(1000, this);
        this.timer.start();
        this.setVisible(true);
        this.setDoubleBuffered(true);
    }

    public void updateTime() {
        if (time > 0) {
            time--;
        }
    }

    public void paint(Graphics page) {

        super.paint(page);

        page.setFont(new Font("TimesRoman", Font.PLAIN, 30));
        String sTime = String.valueOf(time);
        String sRound = String.valueOf(round);


        page.setColor(Color.WHITE);
        page.drawString(sTime, 253, 149);
        page.drawString(sRound, 230, 105);
    }

    public void actionPerformed(ActionEvent event) {

        this.updateTime();
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Leo D
  • 13
  • 2
  • call `repaint` from `updateTime` – John Dvorak Mar 23 '13 at 07:44
  • Yesss!!!!! thank you. You must've guessed it already, I'm a still noob at java. Again, thank you! :) – Leo D Mar 23 '13 at 07:48
  • Frankly, I'm surprised I didn't find a duplicate question. Anyways, see this: http://stackoverflow.com/questions/10768619/paint-and-repaint-in-java?rq=1 – John Dvorak Mar 23 '13 at 07:54
  • 1
    "Swing programs should override `paintComponent()` instead of overriding `paint()`."—[*Painting in AWT and Swing: The Paint Methods*](http://www.oracle.com/technetwork/java/painting-140037.html#callbacks). – trashgod Mar 23 '13 at 10:39

1 Answers1

1
public void updateTime(){
    if (time>0) time--;
}

When time is changed, your component should be redrawn. However, Swing normally thinks of components as static objects, and doesn't redraw them continuously. You need to tell Swing that you want your component repainted:

public void updateTime(){
    if (time>0){
        time--;
        this.repaint();
    }
}

On a side note, perhaps you should stop your timer when you reach zero. It seems no longer used.

John Dvorak
  • 26,799
  • 13
  • 69
  • 83