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
}
}
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 need to write a program that uses a swing countdown timer to do something (in this case, print out a String in the console). It gets the needed delay info from a spinner and executes the code when I hit the Start button. However, when I enter a value in the spinner, it just waits for twice that many seconds and finishes the run without printing out anything.
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
int x = (int) Spinner1.getValue() * 1000;
Timer TIMER = new Timer(x, new MyActionListener());
TIMER.start();
try {
Thread.sleep(x * 2);
} catch (InterruptedException e) {
}
TIMER.stop();
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Something");
}
}
Any help would be greatly appreciated!
The problem is that you are locking out yourself.
With
Thread.sleep(x * 2);
you are blocking the EventDispatchThread that would run your ActionListener. Still the timer internally keeps a flag that the timeout occured and that it should run your ActionListener at the next possible time.
But
TIMER.stop();
is resetting the TIMER, so that the notification is lost.
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.
I have a JTextField that is cleared if it has invalid content. I would like the background to flash red one or two times to indicate to the user that this has happened. I have tried:
field.setBackground(Color.RED);
field.setBackground(Color.WHITE);
But it is red for such a brief time that it cannot possibly be seen. Any tips?
The correct solution, almost arrive at by just eric, is to use a Swing Timer, since all the code in the Timer's ActionListener will be called on the Swing event thread, and this can prevent intermittent and frustrating errors from occurring. For example:
public void flashMyField(final JTextField field, Color flashColor,
final int timerDelay, int totalTime) {
final int totalCount = totalTime / timerDelay;
javax.swing.Timer timer = new javax.swing.Timer(timerDelay, new ActionListener(){
int count = 0;
public void actionPerformed(ActionEvent evt) {
if (count % 2 == 0) {
field.setBackground(flashColor);
} else {
field.setBackground(null);
if (count >= totalCount) {
((Timer)evt.getSource()).stop();
}
}
count++;
}
});
timer.start();
}
And it would be called via flashMyField(someTextField, Color.RED, 500, 2000);
Caveat: code has been neither compiled nor tested.
You need to extend public class Timer
Do it like so:
private class FlashTask extends TimerTask{
public void run(){
// set colors here
}
}
You can set Timer to execute in whatever intervals you prefer to create the flashing effect
From documentation:
public void scheduleAtFixedRate(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay.
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);
}
}