find how long swing timer has been running - java

I'm making a stop watch and I know how to do everything, except find how long my timer object has been going. Is there a method like timer.getElapsedTime() or something of that nature?
Edit: There are numbers saying 00 00 00. Every second it needs to increment. My thought process is seconds = timer.getElapsedTime();
secs.setText(seconds)

Just save System.currentTimeMillis() in some variable when you set your timer, and compare the value to the current return value when you need the elapsed time.
EDIT: Make the timer fire once every second. Note that we re-set the timer every time it fires to prevent lag and processing time from accumulating.
package timertest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class TimerTest implements ActionListener {
JLabel timeDisplay;
long startTime;
Timer timer;
int seconds;
public void createAndShowGUI() {
JFrame frame=new JFrame("Stopwatch");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeDisplay=new JLabel("0");
frame.getContentPane().add(timeDisplay);
frame.pack();
frame.setVisible(true);
startTime=System.currentTimeMillis();
seconds=1;
timer=new Timer(1000, this);
timer.setRepeats(false);
timer.start();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TimerTest().createAndShowGUI();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
long now=System.currentTimeMillis();
long elapsed=now-startTime;
seconds++;
timeDisplay.setText(elapsed+" Milliseconds since start");
timer.setInitialDelay((int)(startTime+seconds*1000-now));
timer.start();
}
}

You can make your own timer class. (Or inherit from the current timer class and add this functionality)
public class Timer
{
private long startTime = 0;
public void start()
{
startTime = System.currentTimeMillis();
}
public int getElapsedTime()
{
return (System.currentTimeMillis() - startTime) / 1000 //returns in seconds
}
}

Related

How to display seconds of the timer in the output screen?

import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;
public class Java {
Toolkit toolkit;
Timer timer;
int t=10000,total;
public Java(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
total =seconds * t;
System.out.println(total);
timer.schedule(new RemindTask(), total);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
System.exit(0);
}
}
public static void main(String args[]) {
new Java(5);
System.out.println("Timer started");
}
}
How can I display the seconds similar to countdown timer in output screen, I want to use it in a quiz program
0:53 => 0:52 like this ...
What you can do is schedule a task at a fixed rate (Timer.scheduleAtFixedRate) using a period of 1 second. As far as possible, we should refrain from calling the System.exit(0) and wait for the threads to complete their tasks. We can make the main thread (the thread that started the timer) sleep for the duration of the timer tasks and then when it finally wakes up, it cancels the timer:
private final Timer timer;
public CountDownTimer(int seconds) {
timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(seconds), 0, 1000);
}
class RemindTask extends TimerTask {
private volatile int remainingTimeInSeconds;
public RemindTask(int remainingTimeInSeconds) {
this.remainingTimeInSeconds = remainingTimeInSeconds;
}
public void run() {
if (remainingTimeInSeconds != 0) {
System.out.println(remainingTimeInSeconds + " ...");
remainingTimeInSeconds -= 1;
}
}
}
public static void main(String args[]) throws InterruptedException {
CountDownTimer t = new CountDownTimer(5);
System.out.println("Timer started");
Thread.sleep(5000);
t.end();
}
private void end() {
this.timer.cancel();
}

Why does my java timer stop after seemingly random number of iterations?

I am trying to create a simple java program that will run indefinitely and output a number every second. I believe my code here should do this; however, it stops after the variable i gets to either 2, 3 or 4. Randomly. Most of the time it hits 3. I do not think that the program stopping is based on i at all, but something i'm overlooking perhaps.
All this program needs to do is spit out the second count using a timer. I feel like my code might be a little over complicated so please let me know if i'm making it too hard.
package testing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class driver {
static int delay = 1000; //milliseconds
private Timer timer;
int i = 0;
public driver(){
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println(i);
i++;
}
};
timer = new Timer(delay, taskPerformer);
timer.setInitialDelay(0);
timer.start();
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new driver();
}
});
}
}
Everything is just right in your program, but one.
Your program starts (from main() obviously), which starts the timer, timer method initiates the process of displaying time/number every second, and after that, the main thread dies! resulting in completion of program execution.
So to avoid this you simply can keep main thread busy.
Here's the simplest way :
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
driver d = new driver();
}
});
for(;;); // <-- **Check this out :D**
}

Counting and printing time in java using swing

I'm trying to implement a timer using one thread and print it on a JButton using another thread.
my class for time is like this:
public class Time extends Thread
{
int counter = 0;
public String currentTime = new String();
public String printFormat(int second)
{
return String.format("%d:%d", second/60, second%60);
}
synchronized public void count(int minute) throws InterruptedException
{
minute *= 60;
while(minute >= 0)
{
wait(1000);
minute--;
currentTime = printFormat(minute);
System.out.println(currentTime);
}
}
and my main thread is like this:
button.setText(time.currentTime);
what is wrong with this piece of code?
"if you can explain it using java swing timer , I would appreciate that"
If you want to use a javax.swing.Timer do the following, it really simple.
The same way you set a ActionListener to a button, you do the same for the timer. Except instead of the button firing the event, it's fired by the timer, every duration period you set for it.
In the case of a clock like timer, you would set it to 1000,
indication do something every 1000 milliseconds.
In this particular
example, I just set the text of the button with a count value that I
increment by one every time the timer event is fired. Heres the Timer code
Timer timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
button.setText(String.valueOf(count));
count++;
}
});
timer.start();
As you can see it' pretty simple
You can run this example
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ButtonTimer {
private JButton button = new JButton(" ");
private int count = 1;
public ButtonTimer() {
Timer timer = new Timer(1000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
button.setText(String.valueOf(count));
count++;
}
});
timer.start();
JFrame frame = new JFrame();
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonTimer();
}
});
}
}
If you want help trying to figure out your current code, consider posting a runnable program we can test out. So we can see where you're going wrong.
Here's a tutorial on Concurrency With Swing

How to use Timer

I have an application made in Netbeans and I don't have any idea how to use a Timer in Java. In Winform there's a control box of Timer which is drag and use only. Now I want to use a timer for 1 seconds after about.setIcon(about4); (which is GIF) is executed.
import javax.swing.ImageIcon;
int a2 = 0, a3 = 1, a4 = 2;
ImageIcon about2 = new ImageIcon(getClass().getResource("/2What-is-the-Game.gif"));
about2.getImage().flush();
ImageIcon about3 = new ImageIcon(getClass().getResource("/3How-to-play.gif"));
about3.getImage().flush();
ImageIcon about4 = new ImageIcon(getClass().getResource("/4About-end.gif"));
about4.getImage().flush();
if(a2 == 0)
{
a2=1;
a3=1;
about.setIcon(about2);
}
else if (a3 == 1)
{
a3=0;
a4=1;
about.setIcon(about3);
}
else if (a4 == 1)
{
a4=0;
a2=0;
about.setIcon(about4);
}
}
How can I achieve this?
In Java, we have several ways of Timer implementation or rather its uses, a few of them are-
To set up a specific amount of delay until a task is executed.
To find the time difference between two specific events.
Timer class provides facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
public class JavaReminder {
Timer timer;
public JavaReminder(int seconds) {
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new RemindTask(), seconds*1000); //delay in milliseconds
}
class RemindTask extends TimerTask {
#Override
public void run() {
System.out.println("ReminderTask is completed by Java timer");
timer.cancel(); //Not necessary because we call System.exit
//System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("Java timer is about to start");
JavaReminder reminderBeep = new JavaReminder(5);
System.out.println("Remindertask is scheduled with Java timer.");
}
}
Read more from here:
http://javarevisited.blogspot.in/2013/02/what-is-timer-and-timertask-in-java-example-tutorial.html
http://www.javatutorialhub.com/timers-java
Declare an instance of java.util.Timer in your code (in the constructor?) and configure/control it with the methods found in the docs.
import java.util.Timer;
import java.util.TimerTask;
...
private Timer t;
public class MyClass()
{
t=new Timer(new TimerTask(){
#Override
public void run()
{
//Code to run when timer ticks.
}
},1000);//Run in 1000ms
}

Java TimerTick event for game loop

I tried making a game loop in Java using the Timer from java.util.Timer. I am unable to get my game loop to execute during the timer tick. Here is an example of this issue. I am trying to move the button during the game loop, but it is not moving on the timer tick event.
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JButton;
public class Window extends JFrame {
private static final long serialVersionUID = -2545695383117923190L;
private static Timer timer;
private static JButton button;
public Window(int x, int y, int width, int height, String title) {
this.setSize(width, height);
this.setLocation(x, y);
this.setTitle(title);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
timer = new Timer();
timer.schedule(new TimerTick(), 35);
button = new JButton("Button");
button.setVisible(true);
button.setLocation(50, 50);
button.setSize(120, 35);
this.add(button);
}
public void gameLoop() {
// Button does not move on timer tick.
button.setLocation( button.getLocation().x + 1, button.getLocation().y );
}
public class TimerTick extends TimerTask {
#Override
public void run() {
gameLoop();
}
}
}
Since this is a Swing application, don't use a java.util.Timer but rather a javax.swing.Timer also known as a Swing Timer.
e.g.,
private static final long serialVersionUID = 0L;
private static final int TIMER_DELAY = 35;
in the constructor
// the timer variable must be a javax.swing.Timer
// TIMER_DELAY is a constant int and = 35;
new javax.swing.Timer(TIMER_DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
gameLoop();
}
}).start();
and
public void gameLoop() {
button.setLocation(button.getLocation().x + 1, button.getLocation().y);
getContentPane().repaint(); // don't forget to repaint the container
}
First of all, Timer.schedule schedules the task for one execution, not for repeated executions. So this program can only make the button move once.
And you have a second problem : all the interactions with swing components should be done in the event dispatch thread, and not in a background thread. Read http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading for more details. Use a javax.swing.Timer to perform swing actions at repeated intervals.

Categories