I can't seem to get this timer to go off. the program compiles and from my understanding this should ping every 1000ms or 1 second and perform the lines in the actionPerformed{} function.
public void stringGeneration(String args[]){
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String fullIstring = java.lang.String.valueOf(injectString[0] + injectString[1] + injectString[2] + injectString[3] + injectString[4]);
jLabel3.setText(fullIstring);
System.out.println("output");
}
};
Timer timer = new Timer(1000, taskPerformer);
timer.setRepeats(true);
timer.start();
//Thread.sleep(500);
}
i just gave you an example and not something to copy paste. But you can try this if you want to try as is. In your case the above example should look like:
class HeartBeatTask extends TimerTask {
private int timerInterval;
public HeartBeatTask(int timeInterval)
{
this.timerInterval = timeInterval;
}
public void run()
{
String fullIstring = java.lang.String.valueOf(injectString[0] + injectString[1] + injectString[2] + injectString[3] + injectString[4]);
jLabel3.setText(fullIstring);
System.out.println("output");
}
}
Your method will then call the above class like this:
public void stringGeneration(String args[]){
HeartBeatTask tt = new HeartBeatTask();
t1.schedule(tt, 0, 1000 * 60 * 2);
}
This is how i would to a scheduled task in java:
import java.util.TimerTask;
class HeartBeatTask extends TimerTask
{
private int timerInterval;
public HeartBeatTask(int timeInterval)
{
this.timerInterval = timeInterval;
}
public void run()
{
// Your function call to schedule here
}
public static void main(String[] args)
{
java.util.Timer t1 = new java.util.Timer();
HeartBeatTask tt = new HeartBeatTask();
t1.schedule(tt, 0, 1000 * 60 * 2);
}
}
Hope that helps
Related
I am trying execute two jobs simultaneously. One of the things that I am trying to do is displaying a count up timer and the other one is moving the ball.
This is where I create the timer and also call the moveBall method
button.addChangeListener(new ChangeListener() {
int start = 0;
public void stateChanged(ChangeEvent e) {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
timeValue.setText(++start + " sec");
}
};
timer = new Timer(1000, taskPerformer);
timer.start();
ball.moveBall();
}
});
This is my moveBall method
public void moveBall() {
Thread ball = new Thread() {
double counter = 0;
int t = (int) (2 * Vy / 9.8);
public void run() {
try {
while (t >= 0) {
// calculate Vx and Vy
Ball.this.setX(Ball.this.getX() + Vx);
Ball.this.setY(Ball.this.getY() - Vy);
counter += 50;
if (counter == 1000) {
t--;
counter = 0;
}
paintingComponent.repaint();
Thread.sleep(20);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
ball.start();
}
When I execute the above code the label for displaying the time passed is not changing at all during the ball is moving and when the movement is over it takes the last number that it supposed to take.
This is a example two executions of two threads, Java simultaneous execution
public class ThreadExecutor extends Thread {
private String name;
private int executionCount;
public ThreadExecutor(final String name, final int executionCount) {
this.name = name;
this.executionCount = executionCount;
}
#Override
public void run() {
int count = 1;
while (count <= executionCount) {
System.out.println("Executing thread ".concat(name).concat(" : ") + count);
count++;
}
}
}
public class Main {
public static void main(String args[]) {
final ThreadExecutor one = new ThreadExecutor("One", 1);
final ThreadExecutor two = new ThreadExecutor("Two", 2);
one.start();
two.start();
}
}
I want to use TimerTask for Sleep, but I am unable to run this code.
The run function is called for the first time, and then it waits infinitely. Is there any issue with my code?
import java.util.Timer;
import java.util.TimerTask;
public class TimeExecutor {
class LocalSleep extends TimerTask {
private int noOfSeconds;
private int count = 0;
private Timer timer;
public LocalSleep(int noOfSeconds, Timer timer) {
this.noOfSeconds = noOfSeconds;
this.timer = timer;
}
void sleeeep() {
if (count < noOfSeconds) {
System.out.println("Count: " + count);
count++;
} else
timer.cancel();
}
#Override
public void run() {
sleeeep();
}
}
public static void main(String args[]) {
Timer timer = new Timer();
TimeExecutor t = new TimeExecutor();
timer.schedule(t.new LocalSleep(5, timer), 1000);
}
}
Working after replacing
timer.schedule(t.new LocalSleep(5, timer), 1000);
with:
timer.schedule(t.new LocalSleep(5, timer), 0, 1000);
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.
I have a GUI with a form for people to fill up and I would like to put a countdown timer at the top right hand corner of the page
Heres the method for the timer to get the remaining time. Say my form class is FillForm and the timer method is found in Timer.
How do I put a dynamic (constantly updating) timer inside of the GUI?
public String getRemainingTime() {
int hours = (int)((this.remainingTime/3600000) % 60);
int minutes = (int)((this.remainingTime/60000) % 60);
int seconds = (int)(((this.remainingTime)/1000) % 60);
return(format.format(hours) + ":" + format.format(minutes)+
":" + format.format(seconds));
}
GUI is built using NetBeans GUI builder.
Try This :
import javax.swing.Timer;
Timer timer=new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//code here
}
});
timer.start();
//timer.stop()
Every one Seconds Timer Execute.
Try This Demo :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
class Counter {
private static int cnt;
static JFrame f;
public static void main(String args[]) {
f=new JFrame();
f.setSize(100,100);
f.setVisible(true);
ActionListener actListner = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cnt += 1;
if(cnt%2==0)
{
f.setVisible(true);
}
else
{
f.setVisible(false);
}
}
};
Timer timer = new Timer(500, actListner);
timer.start();
}
}
You should abstract your timer into a UI component. JLabel seems the most suited as it is a text that you want to display.
public class TimerLabel extends JLabel {
// Add in your code for 'format' and 'remainingTime'.
// Note that the first time that 'getText' is called, it's called from the constructor
// if the superclass, so your own class is not fully initialized at this point.
// Hence the 'if (format != null)' check
public TimerLabel() {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();
}
public String getRemainingTime() {
int hours = (int) ((this.remainingTime / 3600000) % 60);
int minutes = (int) ((this.remainingTime / 60000) % 60);
int seconds = (int) (((this.remainingTime) / 1000) % 60);
return (format.format(hours) + ":" + format.format(minutes) + ":" + format.format(seconds));
}
#Override
public String getText() {
if (format != null) {
return getRemainingTime();
} else {
return "";
}
}
"Could i add this into a Swing.JPanel or something?"
Just put it in the constructor of your form class. Declare the Timer timer; as a class member and not locally scoped so that you can use the start() method like in a button's actionPerformed. Something like
import javax.swing.Timer;
public class GUI extends JFrame {
public Timer timer = null;
public GUI() {
timer = new Timer (500, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (timerGetsToZero) {
((Timer)e.getSource()).stop();
} else {
timeLabel.setText(getRemainingTime());
}
}
});
}
private void startButtonActionPerformed(ActionEvent e) {
timer.start();
}
}
I'm trying to use a progress bar similar to this one below in Java:
public class MyProgressSplashScreen extends JWindow
{
private final JProgressBar progressbar;
private final ExecutorService autoProgressExecutor = Executors.newFixedThreadPool(1);
public MyProgressSplashScreen(final int theMin, final int theMax)
{
super();
final JPanel contentPanel = new JPanel(new BorderLayout());
contentPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
if (theMin != -1 && theMax != -1)
{
progressbar = new JProgressBar(SwingConstants.HORIZONTAL, theMin, theMax);
}
else
{
progressbar = new JProgressBar(SwingConstants.HORIZONTAL);
progressbar.setIndeterminate(true);
}
progressbar.setStringPainted(true);
contentPanel.add(progressbar, BorderLayout.SOUTH);
add(contentPanel);
pack();
setAlwaysOnTop(true);
}
public void showProgress(final int theValueTo, final int theEstimatedTimeInSeconds)
{
showProgress(progressbar.getValue(), theValueTo, theEstimatedTimeInSeconds);
}
public void showProgress(final int theValueFrom, final int theValueTo,
final int theEstimatedTimeInSeconds)
{
setVisible(true);
autoProgressExecutor.execute(new Runnable()
{
#Override
public void run()
{
int numberOfSteps = theValueTo - theValueFrom;
long timeToWait = TimeUnit.SECONDS.toMillis(theEstimatedTimeInSeconds)
/ numberOfSteps;
for (int i = theValueFrom; i <= theValueTo; i++)
{
progressbar.setValue(i);
try
{
TimeUnit.MILLISECONDS.sleep(timeToWait);
}
catch (final InterruptedException e) { }
}
if (progressbar.getValue() == 100) { setVisible(false); }
}
});
}
}
I am however not able to pass a copy of the MyProgressSplashScreen in order to let a separate thread update the progress.
For instance the program below starts counting from 0 to 10 and then restarts from 0 to 30 while it shouldn't reset to zero!
public class TestSplashScreen
{
private final MyProgressSplashScreen myProgressSplashScreen = new MyProgressSplashScreen(-1,-1);
public static void main(String args[])
{
TestSplashScreen testInvoke = new TestSplashScreen();
testInvoke.synchronize();
}
public void synchronize()
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
myProgressSplashScreen.showProgress(10, 2);
myProgressSplashScreen.toFront();
MyRunnable myRunnable = new MyRunnable();
myRunnable.setSyncProgressSplashScreen(myProgressSplashScreen);
Thread t1 = new Thread(myRunnable);
t1.start();
}
};
runnable.run();
}
}
class MyRunnable implements Runnable
{
MyProgressSplashScreen syncProgressSplashScreen;
public void setSyncProgressSplashScreen(MyProgressSplashScreen syncProgressSplashScreen)
{
this.syncProgressSplashScreen = syncProgressSplashScreen;
}
#Override
public void run()
{
syncProgressSplashScreen.showProgress(30, 3);
}
}
The problem is you call syncProgressSplashScreen.showProgress 2 times. The first time it blocks the thread causing it to increment from 0 to 10 then you call it again going from 0 to 30. Remove the line that reads myProgressSplashScreen.showProgress(10, 2); and it wont do it 2 times. Also I noticed you dont set your maximum value for the progress bar so unless you call myProgressSplashScreen.showProgress(100, 2) it wont go to 100%.