Using timer to count as a stopwatch in Java Applet - java

I'm wanting to create a stopwatch so to speak in order to score my game. Lets say I have a variable: int sec = 0. When the game starts I want a g.drawString to draw the time to the applet. So for example each second, sec will increment by 1.
How do I go about making it g.drawString(Integer.toString(sec), 40, 400) increment by 1 and draw each second?
Thanks.
EDIT:
I've figured out how to increment it and print it to the screen by using ActionListener and putting g.drawString in there but it prints ontop of each other. If I put g.drawString into the paint method and only increment sec by 1 in the ActionListener there is a a flicker. Should I use Double Buffering? If so how do I go about doing this?

import java.awt.event.*;
import javax.swing.*;
public class StopWatch extends JLabel
implements MouseListener, ActionListener {
private long startTime; // Start time of stopwatch.
// (Time is measured in milliseconds.)
private boolean running; // True when the stopwatch is running.
private Timer timer; // A timer that will generate events
// while the stopwatch is running
public StopWatch() {
// Constructor.
super(" Click to start timer. ", JLabel.CENTER);
addMouseListener(this);
}
public void actionPerformed(ActionEvent evt) {
// This will be called when an event from the
// timer is received. It just sets the stopwatch
// to show the amount of time that it has been running.
// Time is rounded down to the nearest second.
long time = (System.currentTimeMillis() - startTime) / 1000;
setText("Running: " + time + " seconds");
}
public void mousePressed(MouseEvent evt) {
// React when user presses the mouse by
// starting or stopping the stopwatch. Also start
// or stop the timer.
if (running == false) {
// Record the time and start the stopwatch.
running = true;
startTime = evt.getWhen(); // Time when mouse was clicked.
setText("Running: 0 seconds");
if (timer == null) {
timer = new Timer(100,this);
timer.start();
}
else
timer.restart();
}
else {
// Stop the stopwatch. Compute the elapsed time since the
// stopwatch was started and display it.
timer.stop();
running = false;
long endTime = evt.getWhen();
double seconds = (endTime - startTime) / 1000.0;
setText("Time: " + seconds + " sec.");
}
}
public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
} // end StopWatchRunner
A small applet to test the component:
/*
A trivial applet that tests the StopWatchRunner component.
The applet just creates and shows a StopWatchRunner.
*/
import java.awt.*;
import javax.swing.*;
public class Test1 extends JApplet {
public void init() {
StopWatch watch = new StopWatch();
watch.setFont( new Font("SansSerif", Font.BOLD, 24) );
watch.setBackground(Color.white);
watch.setForeground( new Color(180,0,0) );
watch.setOpaque(true);
getContentPane().add(watch, BorderLayout.CENTER);
}
}

Related

Java GUI stopwatch not displaying time

I've been working on this stopwatch application for a decent amount of time now but I've encountered some problems.
Problems
The stopwatch isn't starting properly probably due to the clock logic
The stopwatch isn't displaying the numbers onto my Java program properly
It would be nice if anyone were to help explain the flaws in my program and tell me why it isn't working the way I would like it to be. Much help needed and appreciated so here is my code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Clock {
private static void createWindow() {
// Important
final int windowWidth = 800; // Window width
final int windowHeight = 300; // Window height
// Clock variables
boolean clockRunning = true; // When clock is running, this will be true
int milliseconds = 0;
int seconds = 0;
int minutes = 0;
int hours = 0;
// Create JFrame
JFrame frame = new JFrame(); // JFrame object
// Create timer text
JLabel timer = new JLabel("00:00:00");
timer.setText("00:00:00");
timer.setBounds(355, 100, 100, 40); // Button position
// JButtons
JButton startTimer = new JButton("Start the timer"); // Start timer button
JButton stopTimer = new JButton("Stop the timer"); // Stop timer button
// Event listeners
startTimer.addActionListener(new ActionListener() // Start timer
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Timer has started");
}
});
stopTimer.addActionListener(new ActionListener() // Stop timer
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println("Timer has stoped");
}
});
// Clock logic
if (clockRunning = true) {
milliseconds = 0;
seconds++;
}
if(milliseconds > 1000) {
milliseconds=0;
seconds++;
}
if(seconds > 60) {
milliseconds=0;
seconds=0;
minutes++;
}
if(minutes > 60) {
milliseconds=0;
minutes=0;
hours++;
}
timer.setText(" : " + seconds); // Milliseconds
timer.setText(" : " + milliseconds); // Seconds
timer.setText(" : " + minutes); // Minutes
timer.setText("" + hours); // Hours
// JButton Settings
startTimer.setBounds(10, 100, 200, 30); // Button position
stopTimer.setBounds(570, 100, 200, 30); // Button position
// Frame Settings
frame.setSize(windowWidth, windowHeight); // Window size
frame.setLayout(null); // Frame position
// Add
frame.add(startTimer);
frame.add(stopTimer);
frame.add(timer);
// Frame settings
frame.setVisible(true); // Make frame visible
frame.setResizable(false); // Disables maximize
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Allows the window to be closed
}
public static void main(String[] args) {
createWindow();
}
}
The stopwatch isn't displaying the numbers onto my Java program properly
timer.setText(" : " + seconds); // Milliseconds
timer.setText(" : " + milliseconds); // Seconds
timer.setText(" : " + minutes); // Minutes
timer.setText("" + hours); // Hours
The setText(…) method replaces the existing text.
So the above code is the same as:
timer.setText("" + hours); // Hours
The stopwatch isn't starting properly probably due to the clock logic
For a stop watch you will need to use a Swing Timer so you can update the text at a specified interval.
See: Program freezes during Thread.sleep() and with Timer for the basics of using a Timer.

Get javax swing timer value

I'm trying to program a game where I output the time (in milliseconds) the player has been alive. I thought I can just use a timer and gets it value pretty easily.
public class InvaderPanel extends JPanel implements KeyListener,ActionListener {
private int timealive; //in ms, max value 2147483647 --->3.5 weeks
private Timer timer=new Timer(30,this); //I think it(30) should be 1 right ?
/**
* Create the panel.
*/
public InvaderPanel() {
addKeyListener(this);
setFocusable(true);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if(playerdead){
timer.stop;
timealive=timer.value; // <--- That's what I'm looking for.
}
}
}
But here lies my problem: timer.value doesn't exist, so how do I get the value of my timer in milliseconds ?
Here is my solution for you. You need to create timer which exactly ticks 1 time per second. And each tick when player is alive increase the value of timealive variable. I have another solution for you, but I think this should be enough.
public class InvaderPanel extends JPanel implements KeyListener,ActionListener {
private int timealive; //in ms, max value 2147483647 --->3.5 weeks
private Timer timer=new Timer(1000,this); // 1000ms = 1 second, but you
// can also set it to 30ms.
/**
* Create the panel.
*/
public InvaderPanel() {
addKeyListener(this);
setFocusable(true);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if(playerdead){
timer.stop();
// here we can use timealive value
} else {
// timealive++; if you want to get the value in seconds
// in this case the timer delay must be 1000ms
timealive += timer.getDelay(); // if you want to get the value in milliseconds
}
}

Countdown timer helppp

I made a puzzle game in java Applet, and I need to add a timer that runs for 5 minutes where the player has to solve the puzzle within this time, if not a dialog box will appear asking to retry, so then I need the timer to start again.
Can someone tell me how can I code this.
public void init (){
String MINUTES = getParameter("minutes");
if (MINUTES != null) remaining = Integer.parseInt(MINUTES) * 600000;
else remaining = 600000; // 10 minutes by default
// Create a JLabel to display remaining time, and set some PROPERTIES.
label = new JLabel();
// label.setHorizontalAlignment(SwingConstants.CENTER );
// label.setOpaque(false); // So label draws the background color
// Now add the label to the applet. Like JFrame and JDialog, JApplet
// has a content pane that you add children to
count.add(label);
Puzframe.add(count,BorderLayout.SOUTH);
// Obtain a NumberFormat object to convert NUMBER of minutes and
// seconds to strings. Set it up to produce a leading 0 if necessary
format = NumberFormat.getNumberInstance();
format.setMinimumIntegerDigits(2); // pad with 0 if necessary
// Specify a MouseListener to handle mouse events in the applet.
// Note that the applet implements this interface itself
// Create a timer to call the actionPerformed() method immediately,
// and then every 1000 milliseconds. Note we don't START the timer yet.
timer = new Timer(1000, this);
timer.setInitialDelay(0); //
timer.start(); }
public void start() { resume(); }
//The browser calls this to stop the applet. It may be restarted later.
//The pause() method is defined below
void resume() {
// Restore the time we're counting down from and restart the timer.
lastUpdate = System.currentTimeMillis();
timer.start(); // Start the timer
}`
//Pause the countdown
void updateDisplay() {
long now = System.currentTimeMillis(); // current time in ms
long elapsed = now - lastUpdate; // ms elapsed since last update
remaining -= elapsed; // adjust remaining time
lastUpdate = now; // remember this update time
// Convert remaining milliseconds to mm:ss format and display
if (remaining < 0) remaining = 0;
int minutes = (int)(remaining/60000);
int seconds = (int)((remaining)/1000);
label.setText(format.format(minutes) + ":" + format.format(seconds));
label.setForeground(new Color(251,251,254));
label.setBackground(new Color(0,0,0));
// If we've completed the countdown beep and display new page
if (remaining == 0) {
// Stop updating now.
timer.stop();
}
count.add(label);
Puzframe.add(label,BorderLayout.SOUTH); }
This what I have so far, but my problem is that it doesn't appear in my game. I'm calling the updateDisplay() from actionPerformed
Use Swing Timer it is made for such a scenario
//javax.swing.Timer
timer = new Timer(4000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(mainFrame,
"End Of Game",
"5 minutes has passed",
JOptionPane.ERROR_MESSAGE);
}
});
I prepared a simple example to demonstrate it
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingControlDemo {
private JFrame mainFrame;
private JPanel controlPanel;
private Timer timer;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(controlPanel);
mainFrame.setVisible(true);
//javax.swing.Timer
timer = new Timer(4000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(mainFrame,
"End Of Game",
"5 minutes has passed",
JOptionPane.ERROR_MESSAGE);
}
});
}
private void showEventDemo(){
JButton okButton = new JButton("Start Game");
okButton.setActionCommand("OK");
okButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
timer.start();
String command = e.getActionCommand();
if( command.equals( "OK" )) {
System.out.println("Timer started");
}
}
}
}

How can I keep updating a JLabel in ActionListener?

There are two buttons in GUI: "Go" and "Stop". There is also a JLabel "trainInfoDetail". When "Go" is clicked, how do I let the "speed" in JLabel update once per second while the "Stop" button is still listening and always really to terminate the loop? My program, while looping, seems to stack in this loop and disables "Stop" button until it finishes.
myButton1 = new JButton("Go!",icon1);
myButton2 = new JButton("Stop!",icon2);
HandlerClass onClick = new HandlerClass();
myButton1.addActionListener(onClick);
myButton2.addActionListener(onClick);
private class HandlerClass implements ActionListener{
//overwriting
public void actionPerformed(ActionEvent event){
long startTime = System.currentTimeMillis();
long now;
String caller = event.getActionCommand();
if(caller.equals("Go!")){
while(speed < 100){
now = System.currentTimeMillis();
if((now - startTime) >= 1000){
speed += 10;
trainInfoDetail.setText("Speed: "+speed+" mph");
startTime = now;
}
}
}
else if (caller.equals("Stop!")){
speed = 0;
trainInfoDetail.setText("Speed: "+speed+" mph");
}
}
}
after using Timer:
public class HandlerClass implements ActionListener{
//overwriting
public void actionPerformed(ActionEvent event){
String caller = event.getActionCommand();
TimeClass tc = new TimeClass(caller);
timer = new Timer(1000, tc);
timer.setInitialDelay(1000);
timer.start();
}
}
public class TimeClass implements ActionListener{
String caller;
public TimeClass(String caller){
this.caller=caller;
}
//overwriting
public void actionPerformed(ActionEvent event){
if(caller.equals("Go!")){
speed += 10;
trainInfoDetail.setText("Speed: "+speed+" mph");
}
else if (caller.equals("Stop!")){
timer.stop();
}
else{
timer.stop();
//return;
}
}
}
Short answer, use a Swing Timer. See How to use Swing Timers for more details.
Basically, you can setup the Timer to tick every second (or whatever interval you need) and update the state/variables and UI safely, without blocking the UI or violating the thread rules of Swing and you can stop the Timer in your "stop" button simply by calling Timer's stop method
You should also have a look Concurrency in Swing

How to Make a Stopwatch for a quiz system using java

I'm really stuck, thanks to my college.
I need code in Java to have a Stopwatch which shows time in 00:00:00(mm:ss:msms) format. I want to use Key events to run and pause and reset the timer. Like if I press S the stopwatch starts and P pauses and R resets.
the thing is the I also want to add key events on numbers for teams, like if I press 1, the "team 1" flashes, preferably with a beep, and so on with 2 3 4 5. im not able to understand how to do this.
i wrote this to print time in second only just to try...
import java.awt.event.*;
import javax.swing.*;
public class StopWatch2 extends JLabel
implements KeyListener, ActionListener {
private long startTime;
private boolean running;
private Timer timer;
public StopWatch2() {
super(" Press S ", JLabel.CENTER);
addKeyListener(this);
}
public void actionPerformed(ActionEvent evt) {
long time = (System.currentTimeMillis() - startTime) / 1000;
setText(Long.toString(time));
}
public void keyPressed(KeyEvent e) {
int keyCode=e.getKeyCode();
if (keyCode==KeyEvent.VK_S) {
running = true;
startTime = e.getWhen();
setText("Running: 0 seconds");
if (timer == null) {
timer = new Timer(100,this);
timer.start();
}
else
timer.restart();
}
if(keyCode==KeyEvent.VK_P)
{
timer.stop();
running = false;
long endTime = e.getWhen();
double seconds = (endTime - startTime) / 1000.0;
setText("Time: " + seconds + " sec.");
}
}
public void keyTyped(KeyEvent e)
{}
public void keyReleased(KeyEvent e)
{}
}
import java.awt.*;
import javax.swing.*;
public class Test2 extends JApplet {
public void init() {
StopWatch2 watch = new StopWatch2();
watch.setFont( new Font("SansSerif", Font.BOLD, 24) );
watch.setBackground(Color.white);
watch.setForeground( new Color(180,0,0) );
watch.setOpaque(true);
getContentPane().add(watch, BorderLayout.CENTER);
}
}
im trying stuff on my own n m pretty much self taught so im not able to understand whats going wrong
Do you mean something like:
/**
* Stopwatch is a simple timer.
*/
public class Stopwatch {
/**
* Stopwatch() Initialises a stopwatch.
*/
public Stopwatch() {
// Your code here.
}
/**
* elapsed() The elapsed time in milliseconds shown on the stopwatch.
*
* #return double The elapsed time in milliseconds as a double. Returns -1.0 if no meaningful
* value is available, i.e. if the watch is reset or has been started and not stopped.
*/
public double elapsed() {
// Your code here.
}
/**
* start() Starts the stopwatch and clears the previous elapsed time.
*/
public void start() {
// Your code here.
}
/**
* stop() If the stopwatch has been started this stops the stopwatch and calculates the
* elapsed time. Otherwise it does nothing.
*/
public void stop() {
// Your code here.
}
/**
* reset() Resets the stopwatch and clears the elapsed time.
*/
public void reset() {
// Your code here.
}
#Override
public String toString() {
// Your code here.
}
} // end class Stopwatch

Categories