I am trying to make a stopwatch using swing, but it is not working. Here is my code. The Jlabel clock is always displaying -1, which should only happen if it is stopped. Am I using the invokelater properly?
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class sidePanel extends JApplet implements ActionListener{
JPanel pane;
JLabel clock;
JButton toggle;
Timer timer;
StopWatch stopWatch;
public void init()
{
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
clock = new JLabel("00:00");
toggle = new JButton("Start/Stop");
toggle.addActionListener(this);
pane.add(clock);
pane.add(toggle);
timer = new Timer(500, this);
timer.setRepeats(true);
stopWatch = new StopWatch();
add(pane);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == toggle)
{
if(timer.isRunning())
{
stopWatch.endTime = System.currentTimeMillis();
timer.stop();
}
else
{
stopWatch.startTime = System.currentTimeMillis();
timer.start();
}
}
if(e.getSource() == timer)
{
long time = stopWatch.getElapsedTime();
sidePanel.this.clock.setText(String.valueOf(time));
}
}
private class StopWatch{
private long startTime =0;
private long endTime =0;
public boolean isRunning = false;
public void start(){
startTime = System.currentTimeMillis();
isRunning = true;
}
public void end(){
endTime = System.currentTimeMillis();
isRunning = false;
}
public long getElapsedTime()
{
long currentTime = System.currentTimeMillis();
if(isRunning)
return (currentTime - startTime)/1000;
else
return -1;
}
}
}
Working code
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class sidePanel extends JApplet implements ActionListener{
JPanel pane;
JLabel clock;
JButton toggle;
Timer timer;
//StopWatch stopWatch;
boolean pressed = false;
long startTime =0;
long endTime =0;
public void init()
{
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
clock = new JLabel("00:00");
toggle = new JButton("Start/Stop");
toggle.addActionListener(this);
pane.add(clock);
pane.add(toggle);
timer = new Timer(500, this);
timer.setRepeats(true);
//stopWatch = new StopWatch();
add(pane);
}
long cur;
long end;
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == toggle)
{
if(!pressed)
{
timer.start();
startTime = System.currentTimeMillis();
pressed = true;
}
else
{
timer.stop();
pressed = false;
}
}
if(timer.isRunning())
{
endTime = System.currentTimeMillis();
clock.setText(String.valueOf((endTime-startTime)/1000));
}
}
}
Your StopWatch class run once and then terminates...
public void run() {
// Start here
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run() {
long time = getElapsedTime();
sidePanel.this.clock.setText(String.valueOf(time));
}
});
// End here...
}
A thread will terminate when it exists it's run method, in this case, your StopWatch's run method.
What you need to do to is maintain a loop until the isRunning becomes false
public void run() {
while (isRunning) {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run() {
long time = getElapsedTime();
sidePanel.this.clock.setText(String.valueOf(time));
}
});
// Because we really don't want to bombboard the Event dispatching thread
// With lots of updates, which probably won't get rendered any way,
// We put in a small delay...
// This day represents "about" a second accuracy...
try {
Thread.sleep(500);
} catch (Exception exp) {
}
}
}
It would much simpler to use a javax.swing.Timer though...
private Timer timer;
public void init()
{
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
clock = new JLabel("00:00");
toggle = new JButton("Start/Stop");
toggle.addActionListener(this);
pane.add(clock);
pane.add(toggle);
timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
long time = getElapsedTime();
sidePanel.this.clock.setText(String.valueOf(time));
}
});
timer.setRepeats(true);
add(pane);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == toggle)
{
if(timer.isRunning())
{
endTime = System.currentTimeMillis();
timer.stop();
}
else
{
startTime = System.currentTimeMillis();
timer.start();
}
}
}
You can then strip out the functionality from you StopWatch (ie the getElapsedTime())
Related
I'm trying to make a timer that will count up from 00h:00m:00s, with the ability to pause and restart the count from its current time.
Heres the solution I currently have: It will always restart the timer from 0 instead of continuing where it left off. Also, for another inexplicable reason, the hours always display as 07 instead of 00. Does anyone know how I could fix these issues, to have it start counting up from its previous value, and display the correct amount of hours elapsed?
private final SimpleDateFormat date = new SimpleDateFormat("KK:mm:ss");
private long startTime = 0;
private final ClockListener clock = new ClockListener();
private final Timer normalTimer = new Timer(53, clock);
startTimerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(startTime == 0) {
startTime = System.currentTimeMillis();
}
else {
startTime += (System.currentTimeMillis() - startTime);
}
normalTimer.start();
}
});
stopTimerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
normalTimer.stop();
}
});
private void updateClock(){
Date elapsed = new Date(System.currentTimeMillis() - startTime);
timerText.setText(date.format(elapsed));
}
private class ClockListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
updateClock();
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
Your code wasn't runnable, so I created the following GUI.
When you press the "Start" button, the timer starts counting. 37 seconds.
2 minutes, 7 seconds.
1 hour, 6 minutes, 11 seconds.
Pressing the "Pause button pauses the count. Pressing the "Restart" button resumes the count. You can pause and resume the count as many times as you want.
Pressing the "Stop" button stops the counter. You can press the "Reset" button to reset the counter before starting again.
Explanation
When creating a Swing application, using the model-view-controller (MVC) pattern helps to separate your concerns and allows you to focus on one part of the application at a time.
Creating the application model made creating the GUI much easier. The application model is made up of one or more plain Java getter/setter classes.
The CountupTimerModel class keeps long fields to hold the duration in milliseconds and the previous duration. This way, I don't have to pause and restart the Swing Timer.
The duration is the difference between the current time and the start time. I use the System.currentTimeMillis() method to calculate the duration.
The GUI is fairly straightforward.
I made the JButton ActionListeners lambdas. I made the TimerListener a separate class to move the code out of that particular lambda.
Code
Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class CountupTimerGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CountupTimerGUI());
}
private final CountupTimerModel model;
private JButton resetButton, pauseButton, stopButton;
private JLabel timerLabel;
public CountupTimerGUI() {
this.model = new CountupTimerModel();
}
#Override
public void run() {
JFrame frame = new JFrame("Countup Timer GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createDisplayPanel(), BorderLayout.NORTH);
frame.add(createButtonPanel(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createDisplayPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = panel.getFont().deriveFont(Font.BOLD, 48f);
timerLabel = new JLabel(model.getFormattedDuration());
timerLabel.setFont(font);
panel.add(timerLabel);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = panel.getFont().deriveFont(Font.PLAIN, 16f);
resetButton = new JButton("Reset");
resetButton.setFont(font);
panel.add(resetButton);
resetButton.addActionListener(event -> {
model.resetDuration();
timerLabel.setText(model.getFormattedDuration());
});
pauseButton = new JButton("Restart");
pauseButton.setFont(font);
panel.add(pauseButton);
pauseButton.addActionListener(event -> {
String text = pauseButton.getText();
if (text.equals("Pause")) {
model.pauseTimer();
pauseButton.setText("Restart");
} else {
model.startTimer();
pauseButton.setText("Pause");
}
});
Timer timer = new Timer(200,
new CountupListener(CountupTimerGUI.this, model));
stopButton = new JButton("Start");
stopButton.setFont(font);
panel.add(stopButton);
stopButton.addActionListener(event -> {
String text = stopButton.getText();
if (text.equals("Start")) {
model.resetDuration();
model.startTimer();
timer.start();
resetButton.setEnabled(false);
stopButton.setText("Stop");
} else {
model.stopTimer();
timer.stop();
resetButton.setEnabled(true);
stopButton.setText("Start");
}
});
Dimension d = getLargestJButton(resetButton, pauseButton, stopButton);
resetButton.setPreferredSize(d);
pauseButton.setPreferredSize(d);
stopButton.setPreferredSize(d);
pauseButton.setText("Pause");
return panel;
}
private Dimension getLargestJButton(JButton... buttons) {
Dimension largestDimension = new Dimension(0, 0);
for (JButton button : buttons) {
Dimension d = button.getPreferredSize();
largestDimension.width = Math.max(largestDimension.width, d.width);
largestDimension.height = Math.max(largestDimension.height,
d.height);
}
largestDimension.width += 10;
return largestDimension;
}
public JButton getResetButton() {
return resetButton;
}
public JButton getPauseButton() {
return pauseButton;
}
public JButton getStopButton() {
return stopButton;
}
public JLabel getTimerLabel() {
return timerLabel;
}
public class CountupListener implements ActionListener {
private final CountupTimerGUI view;
private final CountupTimerModel model;
public CountupListener(CountupTimerGUI view, CountupTimerModel model) {
this.view = view;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
model.setDuration();
view.getTimerLabel().setText(model.getFormattedDuration());
}
}
public class CountupTimerModel {
private boolean isRunning;
private long duration, previousDuration, startTime;
public CountupTimerModel() {
resetDuration();
}
public void resetDuration() {
this.duration = 0L;
this.previousDuration = 0L;
this.isRunning = true;
}
public void startTimer() {
this.startTime = System.currentTimeMillis();
this.isRunning = true;
}
public void pauseTimer() {
setDuration();
this.previousDuration = duration;
this.isRunning = false;
}
public void stopTimer() {
setDuration();
this.isRunning = false;
}
public void setDuration() {
if (isRunning) {
this.duration = System.currentTimeMillis() - startTime
+ previousDuration;
}
}
public String getFormattedDuration() {
int seconds = (int) ((duration + 500L) / 1000L);
int minutes = seconds / 60;
int hours = minutes / 60;
StringBuilder builder = new StringBuilder();
if (hours > 0) {
builder.append(hours);
builder.append(":");
}
minutes %= 60;
if (hours > 0) {
builder.append(String.format("%02d", minutes));
builder.append(":");
} else if (minutes > 0) {
builder.append(minutes);
builder.append(":");
}
seconds %= 60;
if (hours > 0 || minutes > 0) {
builder.append(String.format("%02d", seconds));
} else {
builder.append(seconds);
}
return builder.toString();
}
}
}
I'm trying to make a counter that counts every 1/100 of a second until the program is closed, but it appears to be a little slower than that. Here's what I have:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
import javax.swing.*;
public class counterTest extends JFrame
{
JLabel label;
long counter = 0;
String counterStr;
public counterTest()
{
super("counter");
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
counter++;
counterStr = Long.toString(counter);
label.setText(counterStr);
}
};
label = new JLabel();
setLayout(new FlowLayout());
setSize(100,100);
setResizable(false);
setVisible(true);
add(label);
javax.swing.Timer timer = new javax.swing.Timer(10, listener);
timer.setInitialDelay(0);
timer.start();
}
public static void main(String args[])
{
counterTest c = new counterTest();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The "10" in the line where I declare "timer" should cause "listener" to run every 1/100 second, correct? It seems a bit slower... what is wrong here?
EDIT: Full code posted.
A Swing Timer is not built to be 100% accurate, and 1/100 may be pushing it's limits. Consider using the Swing Timer but displaying absolute time differences, calculated by getting the time.
e.g.,
private class MyTimerListener implements ActionListener {
private long startTime = 0;
public void reset() {
startTime = System.currentTimeMillis();
}
#Override
public void actionPerformed(ActionEvent e) {
long time = System.currentTimeMillis();
long delta = (time - startTime) / 10L;
label.setText(String.valueOf(delta));
}
}
OK, my mini-program:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyTimer2 extends JPanel implements GuiTimer {
private static final String TIME_FORMAT = "%03d:%03d";
private static final int EXTRA_WIDTH = 50;
private JLabel timerLabel = new JLabel();
private TimerControl timerControl = new TimerControl(this);
public MyTimer2() {
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Time:"));
topPanel.add(timerLabel);
JPanel centerPanel = new JPanel();
centerPanel.add(new JButton(timerControl.getStartAction()));
centerPanel.add(new JButton(timerControl.getStopAction()));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
setDeltaTime(0);
}
#Override
public void setDeltaTime(int delta) {
int secs = (int) delta / 1000;
int mSecs = (int) delta % 1000;
timerLabel.setText(String.format(TIME_FORMAT, secs, mSecs));
}
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = superSz.width + EXTRA_WIDTH;
int prefH = superSz.height;
return new Dimension(prefW, prefH);
}
private static void createAndShowGui() {
MyTimer2 mainPanel = new MyTimer2();
JFrame frame = new JFrame("MyTimer2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
interface GuiTimer {
public abstract void setDeltaTime(int delta);
}
#SuppressWarnings("serial")
class TimerControl {
private static final int TIMER_DELAY = 10;
private long startTime = 0;
private long pauseTime = 0;
private Timer timer;
private GuiTimer gui;
private StartAction startAction = new StartAction();
private StopAction stopAction = new StopAction();
public TimerControl(GuiTimer gui) {
this.gui = gui;
}
public Action getStopAction() {
return stopAction;
}
public Action getStartAction() {
return startAction;
}
enum State {
START("Start", KeyEvent.VK_S),
PAUSE("Pause", KeyEvent.VK_P);
private String text;
private int mnemonic;
private State(String text, int mnemonic) {
this.text = text;
this.mnemonic = mnemonic;
}
public String getText() {
return text;
}
public int getMnemonic() {
return mnemonic;
}
};
private class StartAction extends AbstractAction {
private State state;
public StartAction() {
setState(State.START);
}
public final void setState(State state) {
this.state = state;
putValue(NAME, state.getText());
putValue(MNEMONIC_KEY, state.getMnemonic());
}
#Override
public void actionPerformed(ActionEvent e) {
if (state == State.START) {
if (timer != null && timer.isRunning()) {
return; // the timer's already running
}
setState(State.PAUSE);
if (startTime <= 0) {
startTime = System.currentTimeMillis();
timer = new Timer(TIMER_DELAY, new TimerListener());
} else {
startTime += System.currentTimeMillis() - pauseTime;
}
timer.start();
} else if (state == State.PAUSE) {
setState(State.START);
pauseTime = System.currentTimeMillis();
timer.stop();
}
}
}
private class StopAction extends AbstractAction {
public StopAction() {
super("Stop");
int mnemonic = KeyEvent.VK_T;
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (timer == null) {
return;
}
timer.stop();
startAction.setState(State.START);
startTime = 0;
}
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
long time = System.currentTimeMillis();
long delta = time - startTime;
gui.setDeltaTime((int) delta);
}
}
}
I want to display in my JPanel a JLabel with timer in this mode, for example:
03:50 sec
03:49 sec
....
....
00:00 sec
So I have build this code:
#SuppressWarnings("serial")
class TimeRefreshRace extends JLabel implements Runnable {
private boolean isAlive = false;
public void start() {
Thread t = new Thread(this);
isAlive = true;
t.start();
}
public void run() {
int timeInSecond = 185
int minutes = timeInSecond/60;
while (isAlive) {
try {
//TODO
} catch (InterruptedException e) {
log.logStackTrace(e);
}
}
}
}//fine autoclass
And with this code, I can start the JLabel
TimeRefreshRace arLabel = new TimeRefreshRace ();
arLabel.start();
So I have the time in secondo for example 180 second, how can I create the timer?
Here is an example, how to build a countdown label. You can use this pattern to create your component.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class TimerTest {
public static void main(String[] args) {
final JFrame frm = new JFrame("Countdown");
final JLabel countdownLabel = new JLabel("03:00");
final Timer t = new Timer(1000, new ActionListener() {
int time = 180;
#Override
public void actionPerformed(ActionEvent e) {
time--;
countdownLabel.setText(format(time / 60) + ":" + format(time % 60));
if (time == 0) {
final Timer timer = (Timer) e.getSource();
timer.stop();
}
}
});
frm.add(countdownLabel);
t.start();
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);
}
private static String format(int i) {
String result = String.valueOf(i);
if (result.length() == 1) {
result = "0" + result;
}
return result;
}
}
You could within your try block call the Event Dispatcher Thread (EDT) and update your UI:
try {
SwingUtils.invokeLater(new Runnable() {
#Override
public void run() {
this.setText(minutes + " left");
}
}
//You could optionally block your thread to update your label every second.
}
Optionally, you could use a Timer instead of an actual thread, so your TimerRefreshRace will have its own timer which periodically fires an event. You would then use the same code within your try-catch block to update the UI.
Im making a timer for a game ive created, but Im having a hard time restarting my timer method. It pauses the timer for about a second then continues to count, ex: if the timer is on 4, if the reset button is hit the timer will pause at 4 for a second then resume to 5, 6, etc. Anyway to fix this?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyTimer extends Panel {
private JLabel timeDisplay;
private JButton resetButton;
private JButton startButton;
private JButton stopButton;
Timer timer;
public MyTimer(){
MyTimer timer;
startButton = new JButton("Start Timer");
stopButton = new JButton("Stop Timer");
timeDisplay = new JLabel("...Waiting...");
resetButton = new JButton("Reset Timer");
this.add(resetButton);
this.add(startButton);
this.add(stopButton);
this.add(timeDisplay);
event e = new event();
startButton.addActionListener(e);
event1 c = new event1();
stopButton.addActionListener(c);
event2 d = new event2();
resetButton.addActionListener(d);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
int count = 0;
timeDisplay.setText("Elapsed Time in Seconds: " + count);
TimeClass tc = new TimeClass(count);
timer = new Timer(1000, tc);
timer.start();
}
}
public class TimeClass implements ActionListener{
int counter;
public TimeClass(int counter){
this.counter = counter;
}
public void actionPerformed(ActionEvent e){
counter++;
timeDisplay.setText("Elapsed Time in Seconds: " + counter);
}
}
class event1 implements ActionListener{
public void actionPerformed (ActionEvent c){
timer.stop();
}
}
class event2 implements ActionListener{
public void actionPerformed (ActionEvent d){
timer.restart();
}
}
}
create a global counter in MyTimer class
static volatile int counter;
....
class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
// handle the condition if start button is clicked
// more than once continuously.
if (timer == null) {
TimeClass tc = new TimeClass();
timer = new Timer(1000, tc);
}
timer.start();
}
}
class TimeClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
counter++;
timeDisplay.setText("Elapsed Time in Seconds: " + counter);
}
}
class event1 implements ActionListener {
public void actionPerformed(ActionEvent c) {
// handle the condition if stop is clicked before starting the timer
if (timer != null) {
timer.stop();
}
}
}
class event2 implements ActionListener {
public void actionPerformed(ActionEvent d) {
// reset the counter
counter = 0;
// handle the condition if reset is clicked before starting the timer
if (timer != null) {
timer.restart();
}
}
}
I'm using the swing Timer to make a countdown clock in Netbeans:
public void startTimer() {
System.out.println(right + "value");
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.out.println("action");
timerLabel.setText("" + seconds);
--seconds;
System.out.println(seconds);
if (seconds == -1 && seconds < 0) {
System.out.print("zero");
//displayTimer.stop();
wrong();
dispose();
}
}
};
displayTimer = new Timer(1000, listener);
displayTimer.setInitialDelay(100);
displayTimer.start();
if (right == null) {
System.out.println("null");
} else if (right == true) {
System.out.println("truehere");
displayTimer.stop();
right = null;
seconds = 20;
displayTimer.setDelay(10000);
displayTimer.setInitialDelay(100);
displayTimer.start();
} else if (right == false) {
System.out.print("wrong");
//displayTimer.stop();
seconds = 20;
}
}
I just use System.out.print to test the program, it's not a part of the real program.
I call the stop() method but the timer continues to count. Also, I create a new timer by displayTimer = new javax.swing.Timer(10000, listener); but it counts twice as fast. Can anyone help?
EDIT:
Here is my timer (sort of SSCCE):
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.*;
public class JavaApplication8 {
public static void startTimer() {
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
int seconds = 20;
seconds--;
System.out.println(seconds);
if (seconds == -1 && seconds < 0) {
System.out.print("zero");
}
}
};
Timer displayTimer = new Timer(1000, listener);
displayTimer.setInitialDelay(100);
displayTimer.start();
}
public static void main(String[] args) {
System.out.println("Type win to win!");
startTimer();
String read;
Boolean right;
int seconds;
Scanner scanIn = new Scanner(System.in);
read = scanIn.nextLine();
if (read.equals("win")){
right = true;
}
else{
right = false;
}
if (right == true) {
System.out.println("correct");
//displayTimer.stop();
right = null;
seconds = 20;
//displayTimer.setDelay(10000);
//displayTimer.setInitialDelay(100);
//displayTimer.start();
} else if (right == false) {
System.out.print("incorrect");
//displayTimer.stop();
seconds = 20;
right = null;
}
}
}
it doesn't work right in that the seconds don't show up, but it does show 20 times which is what I want. This is just in its own application, in my real program it is easier to see the problem.
I've noticed that the first time the game runs it works fine. Then I click play again (resets the whole game) and it goes twice as fast. Maybe I'm not resetting something correctly? Here is my reset code:
// Reset Everything
PlayFrame.seconds = 20;
PlayFrame.winnings = 0;
PlayFrame.right = false;
//PlayFrame.displayTimer.stop();
PlayFrame.questionLabel.setText(null);
PlayFrame.count = 0;
WelcomeFrame WFrame = new WelcomeFrame();
WFrame.setVisible(true);
setVisible(false);
PlayFrame P = new PlayFrame();
P.dispose();
if (PlayFrame.seconds == -1 && PlayFrame.seconds < 0){
PlayFrame.displayTimer.stop();
}
}
Its just pseudo code to see how timer can be started and stopped.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.Timer;
public class TimerOnJLabel extends JFrame {
private static final long serialVersionUID = 1L;
long start = System.currentTimeMillis();
long elapsedTimeMillis;
int sec = 5;
Timer timer;
public TimerOnJLabel() {
super("TooltipInSwing");
setSize(400, 300);
getContentPane().setLayout(new FlowLayout());
final JLabel b1;
final JRadioButton jrb = new JRadioButton();
b1 = new JLabel("Simple tooltip 1");
ActionListener timerTask = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
elapsedTimeMillis = System.currentTimeMillis();
b1.setText("Timer : " + (elapsedTimeMillis-start)/1000+" ::::: " +sec);
System.out.println("Timer working: " + sec);
if(--sec == 0){
timer.stop();
System.out.println("Timer Stopped");
}
}
};
timer = new Timer(1000, timerTask);
System.out.println("Timer Started");
timer.start();
getContentPane().add(b1);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]){
new TimerOnJLabel();
}
}
I hope this help.