I've looked many place and can't find out how to refresh automatically my frame. It does work (since i've used many examples already there) when I click buttons, but not automatically.
I want to create a MineSweeper game, and I am adding the Timer in it, everything works except the timer counts, but only updates when a button is clicked. Therefore, simply redoing the layout won't work...
Tough I know my timer works, if I put a System.out in it, i see it at stable second rate.
I will put below a little program, not my game since the code is too long, but a little one I built that is about the same circumstances, fixing it will fix my problem overall.
In this case, i don't have the well developed button from my other program, but the time will only refresh when i'm messing with the window.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ClockTest {
JFrame frame = new JFrame();
JButton test1 = new JButton();
JTextField timer1 = new JTextField();
int hour = 0, min = 0, sec = 0;
String timing;
public ClockTest() {
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(center(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public Component center() {
JPanel pan = new JPanel();
pan.setLayout(new GridLayout(1,2));
test1.setText("Dummy");
timer1.setEditable(false);
timer1.setText(timing);
pan.add(test1);
pan.add(timer1);
return pan;
}
public void count() {
sec++;
if(sec == 60) {
sec -= 60;
min++;
}
if(min == 60) {
min -= 60;
hour++;
}
timing = hour + ":" + min + " : " + sec;
//This is what i do in my game to refresh, to set flags, get mine "exploded"...
//But since i'm not pressing anything... it does not happen.
frame.add(center(), BorderLayout.CENTER);
}
public static void main(String[]args) {
final ClockTest test1 = new ClockTest();
TimerTask task = new TimerTask() {
public void run() {
test1.count();
}
};
Timer t = new Timer();
t.schedule(task,0,1000);
}
}