Hi! I'm very new to this so I have some noobish question.
I want to create a simple GUI with counter going from 10 to 0 and showing that on JLabel not in program output.I'm not sure if that is possible, but here is my code:
import java.util.*;
import java.util.Random;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.*;
public class Test extends JFrame
{
private JLabel peynJl = new JLabel("Countdown ",JLabel.CENTER);
private JButton jbOK = new JButton("START");
public static void main(String [] args)
{
new Test();
}//end of main
public Test()
{
setTitle("Countdown");
JPanel jp1 = new JPanel();
jp1.add(peynJl);
add(jp1, BorderLayout.CENTER);
JPanel jp2 = new JPanel();
jp2.add(jbOK);
add(jp2, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we)
{
dispose();
}
});
jbOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
int i;
for( i=10;i>0;i--)
{
peynJl.setText(""+i);
try
{
Thread.sleep(1000);
}//end of try
catch(Exception e)
{
System.out.println("Sleep error!");
System.exit(0);
}//end of catch
}//end of for loop
if(i==0)
{
JOptionPane.showMessageDialog(null,"Out of time","Counter Reached 0!",JOptionPane.INFORMATION_MESSAGE);
}
}//end of actionPerformed
});//end of new ActionListener
}//enf of constructor
}//end of class
What happens is, this for loop works,I checked, if I set System.out.println(""+i); in the foor loop it will print out every step normally "10,9,8,7..." and with JLabel I don't see that"update" (10,9,8,7..) ,I just get last number set to JLabel (1) after program exits from the for loop.
I apologize if I'm doing some begginers mistake but I would appriciate your help very much.
Thank you in advance.
Toni