Как создать и вывести периодически тикающий таймер в jLabel1? NetBeans - Java
Формулировка задачи:
Т.е. нужно в абсолютно пустой форме JFrame, в метке, секунды чтобы тикали.
А по нажатии на кнопку это время фиксировалось.
Т.е. пустой проект с меткой и кнопкой.
Секунды и минуты - curtime. Сделал 2 кнопки - просто stop и start
А вот когда хочу вывести секунды в метку при нажатии на кнопку, время останавливается/дальше тикает, но присвоения метке не происходит.
Забыл сразу фрагмент кода добавить.
Чтобы на каком-то примере было, я сделал вот так(смотрю старую свою программу):
timer=new Timer(1000, this);
timer.start();public void actionPerformed(ActionEvent e) {
jLabel3.setText("Время: " + curtime2 + " минут " + curtime +" секунд");
curtime++;
if (curtime>=60){
curtime2++;
curtime = 0;
}
if (curtime2>=30) jLabel3.setText("Сделайте перерыв!");
}timer.start();
timer.stop();
jLabel4.setText("" + curtime)Решение задачи: «Как создать и вывести периодически тикающий таймер в jLabel1? NetBeans»
textual
Листинг программы
public class MainTimer extends JFrame {
JPanel jPanel = new JPanel();
private JButton jButton = new JButton("Start");
private JButton jButton2 = new JButton("Stop");
private JLabel jLabel3 = new JLabel();
private JLabel jLabel4 = new JLabel();
private int curtime = 0;
private int curtime2 = 0;
private Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jLabel3.setText("Время: " + curtime2 + " минут " + curtime + " секунд");
curtime++;
if (curtime >= 60) {
curtime2++;
curtime = 0;
}
if (curtime2 >= 30) {
jLabel3.setText("Сделайте перерыв!");
}
timer.start(); // перезапуск таймера
}
});
public MainTimer() throws HeadlessException {
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Timer started.");
timer.start();
}
});
jButton2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Timer stopped.");
jLabel4.setText(" seconds: "+curtime);
timer.stop();
}
});
setLayout(new FlowLayout());
jLabel3.setText("Время: " + curtime2 + " минут " + curtime + " секунд");
jLabel4.setText(" seconds: "+curtime);
jPanel.setLayout(new GridLayout(2,2));
jPanel.add(jLabel3);
jPanel.add(jLabel4);
jPanel.add(jButton);
jPanel.add(jButton2);
add(jPanel,BorderLayout.NORTH);
}
public static void main(String[] args) {
MainTimer jFrame = new MainTimer();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(500,400);
jFrame.setVisible(true);
}
});
}
}