I want to use the method javax.swing.Timer to create a timer that will start at 3:00, then go down to 0:00. I have no idea how to use this method and how to proceed. From now on, I have this code, but I have no idea if it is good. One thing sure is that it doesn't work.
private javax.swing.Timer timer = new javax.swing.Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
int minute = 3;
int seconde = 60;
do {
lblTimer.setText(Integer.toString(seconde));
seconde--;
} while (seconde != 0);
}
});
In this example, a TimerButton responds after the delay passed to the constructor, e.g.
new TimerButton("Back in three minutes", 3 * 60 * 1000));
Your StopListener would take the desired action when the Timer expires, e.g.
private class StopListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
timer.stop();
// further actions here
}
}
See How to Use Swing Timers for additional details.
Related
I'm trying to make a class called timer. The timer class is supposed to be called upon when my character enters the enemy's area. And the timer class is supposed to remove the characters health by 10-health points every 5 seconds. Ive tried multiple different timers but i cant seem to get any of them right. When i tried it removed health but it didn't do it only once, it kept repeating it until the health bar was out of the screen. here is my code:
class Timer {
g = new gubbe();
gubbe g;
Timer timer = new Timer(3000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
g.RemoveHealth();
}
});
timer.setRepeats(false);
timer.start();
}
That is what I've come up with so far.
If any more code is needed just ask.
Here's a class which you can use to time your events:
class Delay {
protected int limit;
public Delay() {limit = millis();}
public Delay (int l) {
limit = millis() + l;
}
public boolean expired () {
if (millis() > limit) { return true; }
return false;
}
}
To check on something every 5 seconds, you would have to initialize it like this:
Delay _delay;
void setup() {
_delay = new Delay(5000);
}
void draw() {
if (_delay.expired()) {
//do something
_delay = new Delay(5000);
}
}
The 5000 is in milliseconds, so it means 5 seconds. If you want to check for a 1 second delay, it would be 1000 instead. We re-initialize it when the delay is finished so it triggers again in 5 more seconds.
Have fun!
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
}
}
Soo created a timer using extending timertask.
label_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
label_1.setVisible(false);
label_2.setVisible(true);
timer.purge();
class MyTimeTask extends TimerTask
{
public void run(){
genReelNumbers();
laa++;
if(laa==50){
timer.cancel();
timer.purge();
laa=0;
label_1.setVisible(true);
label_2.setVisible(false);}}}
timer.purge();
timer.schedule(new MyTimeTask(), 0, 50);}});
But im getting a error with the timer already canceled! As you can see i already tried to use the purge(), soo it cancels the "canceled" timers (dont know if that does make any sence). I want to use this timer each time that i press on the label! Any ideas?
First and foremost, this looks to be a Swing application, and if so, you shouldn't be using java.util.Timer and java.util.TimerTask since Swing is single-threaded, and the two classes above create a new thread or threads to achieve their actions, meaning that important code that should be called on the Swing event thread will not be called on this thread. This this risks causing pernicious intermittent and hard to debug threading exceptions to be thrown. Instead use a javax.swing.Timer. Then to stop this timer, simply call stop() on it, and to restart it, simply call start() on it. For more on this, please read: How To Use Swing Timers.
For example, I'm not 100% sure what you're code is supposed to be doing, but it could look something like:
// warning: code not compile- nor run-tested
label_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
label_1.setVisible(false);
label_2.setVisible(true);
// assuming a javax.swing.Timer field named timer
if (timer != null && timer.isRunning()) {
// if the timer is not null and it's running, stop it:
timer.stop();
}
// TIMER_DELAY is an int constant that specifies the delay between "ticks"
timer = new Timer(TIMER_DELAY, new ActionListener() {
#Override // this method will be called repeatedly, every TIMER_DELAY msecs
public void actionPerformed(ActionEvent e) {
genReelNumbers();
laa++;
if(laa==50){
timer.stop();
// timer.purge();
laa=0;
label_1.setVisible(true);
label_2.setVisible(false);
}
}
});
timer.start();
}
});
after canceling the timer you have no other choice than creating a new object....
I followed the #Hovercraft advice and changed to javax.swing.Timer
It turned out like this:
//The variable "taxa" is the amount of times that i want it to do the task
javax.swing.Timer time1 = new javax.swing.Timer(taxa, new ActionListener() {
public void actionPerformed(ActionEvent e) {
genReelNumbers();
}
});
//starts the timer
time1.start();
//New timertask
TimerTask tt = new TimerTask() {
#Override
public void run() {
//stops the timer
time1.stop();
label_2.setVisible(false);
label_1.setVisible(true);
verificarodas();
}
};
Timer time = new Timer(true);
// the 2000 is how long i want to do the task's
//if i changed to 3000 it would take 3 seconds (remember it has to be a value on miliseconds) to do the 15 times, and soo on
time.schedule(tt, 2000);
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
I want to have a clock showing current time and refreshes every second. The code I am using is:
int timeDelay = 1000;
ActionListener time;
time = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
timeLabel.setText(DateTimeUtil.getTime());
/*timeLabel is a JLabel to display time,
getTime() is samll static methos to return formatted String of current time */
}
};
SwingWorker timeWorker = new SwingWorker() {
#Override
protected Object doInBackground() throws Exception {
new Timer(timeDelay, time).start();
return null;
}
};
timeWorker.execute();
What I want to refresh the timeLabel text in another thread other than EDT.
Am I doing it correct? Any other better way?
Also for information, i've added timeLabel to a extendedJPanel which contains few similar kinds of utilities, and is called in another MainJFrame.
You can do this without a SwingWorker, because this is what the Swing Timer is made for.
int timeDelay = 1000;
ActionListener time;
time = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
timeLabel.setText(DateTimeUtil.getTime());
/* timeLabel is a JLabel to display time,
getTime() is samll static methos to return
formatted String of current time */
}
};
new Timer(timeDelay, time).start();