Witam,
mam mały problem. W poniższym kodzie w klasie "private class StartStopListener" korzystam z javax.swing.Timer. Przycisk "Start" ma startować licznik a "Stop" go stopować. Nie działa mi stopowanie i nie wiem co robię źle. Jeśli w pierwszym if'ie ustawię:
timer.start();
timer.stop();
to nie zastartuje więc stopowanie działa ale jak w drugim if'ie daje
timer.stop()
to nie stopuje i licznik cały czas chodzi mimo, że naciskam przycisk "Stop".
Wie ktoś co jest nie tak ?
package stoper;
import javax.swing.*;
import java.awt.*;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Stoper {
public static void main(String[] args) {
new Ramka();
}
}
class Ramka extends JFrame {
public Ramka() {
setSize(300, 67);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
Container cont = getContentPane();
cont.add(new MainPanel());
}
}
class MainPanel extends JPanel {
JButton
start = new JButton("Start"),
stop = new JButton("Stop");
JLabel timeLabel = new JLabel();
boolean started = false;
boolean paused = false;
static Integer timeElapsed = 0;
public MainPanel() {
timeLabel.setText("<html><b><font size=24>00:00:00");
add(start);
add(stop);
add(timeLabel);
ActionListener startStopListener = new StartStopListener();
start.addActionListener(startStopListener);
stop.addActionListener(startStopListener);
}
private class StartStopListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Timer timer = new Timer(1000, new StartListener());
if(e.getSource() == start) {
if(started == false)
timer.start();
started = true;
} else if(e.getSource() == stop) {
System.out.println("stop");
timer.stop();
}
}
private class StartListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int hours;
int minutes;
int seconds;
String timeToString= "";
++timeElapsed;
hours = timeElapsed/3600;
minutes = (timeElapsed - (hours * 3600))/60;
seconds = timeElapsed - (hours * 3600) - (minutes * 60);
if(hours < 10)
timeToString+= "0" + hours + ":";
else
timeToString+= hours + ":";
if(minutes < 10)
timeToString+= "0" + minutes + ":";
else
timeToString+= minutes + ":";
if(seconds < 10)
timeToString+= "0" + seconds;
else
timeToString+= seconds;
timeLabel.setText("<html><b><font size=24>" + timeToString);
}
}
}
}
</b></b></span></span>