I have a Dialog window with a Button ko and a JLabel l . The button`s label refreshes at 1000ms from 5 to 1. There are 2 problems: the JLabel l it`s not displayed before the counter starts, it`s displayed after that, and the button doesn`t work during the countdown, if i push it during the countdown the window closes(thats the function if the ko button) but only after the countdown finishes. This is the piece of code:

public AskWindow(Frame parinte, boolean modala){
		super(parinte, modala);
		JLabel l;
		int t = 5;
		this.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				MyMain.raspuns = null;
		Panel panel = new Panel();
		ko = new Button("OK");
		l = new JLabel();
		l.setText("ati castigat de "+ nrJocT + " ori");
		add(panel, BorderLayout.SOUTH);
		for (int i=0; i < t; i++)
			ko.setLabel("" + (t-i));
			catch(InterruptedException o){}

Recommended Answers

All 3 Replies

You need to set up a Swing Timer to handle the countdown on the button. See the following on timers:How to Use Timers.

The behavior you are getting right now is because you are sleeping in the thread that is creating the UI. Create the UI first and after it is set visible, start the Timer task that updates the label on the button (and it's behavior if needed).

You could use the following for the countdown

class ButtonCountdown implements ActionListener {
        int count=0;
        JButton button = null;
        public ButtonCountdown(final JButton button, int count){
            this.count = count;
            this.button = button;
        public void actionPerformed(ActionEvent e) {
            if (count>0){
            } else {

and then start it like so after you have the UI all set up

Timer koTimer = new Timer(1000, new ButtonCountdown(ko, 5));

thanks for the help Ezzaral

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.