Search code examples
javaswingcountertoolkit

Java Swing how can I make this counter work?


Everytime my counter reaches 4 I want it to play a beep sound and go back to '1' and again count up to 4 play the beep sound and so on.

I probably shouldn't place this in a label, because the counter doesnt run at all! I don't get any errors but the label says; counter is 4 and doesnt count or anything.

Can you help me make this counter work properly? I also used printline but that gave some errors too.

My code for the counter is this:

button1.addActionListener(new ActionListener() {

  public void actionPerformed(ActionEvent arg0) {

    label1.setVisible(true);
    int counter = 1;

    while(counter < 5 )
    {
      label1.setText("counter  is " + counter);
      counter = counter + 1 ;
    }

    counter = 1;
    tk.beep();
  }
});

Solution

  • Spawn a new thread to count, wait, and update the GUI.

    You're doing all of this work in the Event Dispatch Thread, which is the only thread which updates the GUI. So when you set the text of the label, it doesn't get updated on the screen until the method returns and the Event Dispatch Thread handles the repaint operation.

    You need to spawn a new thread to do this, rather than just running it in a loop which executes immediately. Just have the actionPerformed method spawn a new Thread which handles this instead. Loop, count, and update in this thread, waiting with Thread.sleep between updates. To update the label text, create a new Runnable that will update the label to the next value and put it on the Event Dispatch Thread with SwingUtilities.invokeLater. Keep this thread running in the background until you need it. I would recommend checking a shutdown status boolean every loop through, and quitting when it's set to false. This way, you can shut down the thread cleanly at any time. Or, if you want it to countdown and beep only once, you can have the thread just end after one iteration of counting.

    There are lots of questions on Stack Overflow that detail each of these steps, so I won't repeat this information here.