I was wondering if you guys could help me out. I'm trying to make an animation program with Java's built in graphics module... The thing is, Java executes everything at once; there isn't any time between the different animations. The end product is just the last picture. I need a function that puts like half a second in between each of the pictures.
Any help is appreciated.
Specs: Blue-J, JDK 6.
Edit: Btw, I'm a Java Newbie, and this is a class thing. The assignment was to make an animation, and press 'c' to go forward each frame, but I think thats kinda ghetto, so I want something better.
Create a javax.swing.Timer that executes each X milliseconds, and draws one frame each time it is triggered.
This is the example from the javadoc:
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();
Modify the delay, to e.g. 20ms. That will give you about 50 frames per second if your painting doesn't take too long.
Maybe a simple sleep might be enough for you?
Thread.sleep(milliseconds);
Change your
public static void main(String[] args){ to
public static void main(String[] args) throws InterruptedException {
and inside that method type in
Thread.sleep(milliseconds you want);
Related
I have this loop
while (true) {
game.update();
view.repaint();
Thread.sleep(DELAY);
}
In the game.update various components of the game have their position changed and those updates are reflected when the repaint() method is called on the view. The view extends JComponent and loops through the game objects and calls their print methods.
What I want to do is have a boolean called nextLevel in the game and if it's true Flash text on the screen for the player to notify them that they're going onto the next level. Maybe flash 4-5 times. Then continue the game.
Is this possible? I have been playing around with Thead.Sleep() but this only seems to pause the displaying and in the background the game is still going on.
Any ideas on how to do this?
Maybe you want to avoid threading by using a Timer object.
an example like that could be
int flashTimer = 0;
if(nextLevel) {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
//flash something method here
flashTimer++;
}
});
timer.start();
}
and then check your flashTimer if it reaches the number you want then just stop the timer by timer.stop();
Just an idea which seems to me a bit simpler. the 1000 value is milliseconds which is passed and executes the code inside the actionPerformed method every 1 sec.
Hope it helped
For the sake of learning I've been trying to build a little visualizer (like this one) that shows how different sorting algorithms work. I'm not overly experienced with Swing, and I'm reading that I should use a Timer, but I can't seem to wrap my head around how to actually use it properly.
import javax.swing.Timer;
// .....
public class sortPanel extends JPanel {
private ArrayList<Integer> list;
// .....
public void selectionSort(int msDelay) {
// code here that loops through and sorts the ArrayList.
// I know how to do this part but do not want to start it until I get Timer working.
Timer timer = new Timer(msDelay, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
repaint();
}
});
timer.start();
}
// .....
}
This is what my GUI looks like:
Each of the four panels is an instance of sortPanel. The red circle is the current index of the array the algorithm is on. The start button (for now) calls the selectionSort method in for the first panel.
I was able to get the Timer to work properly when the command was to simply increase the index, but for a more complex task where I want a delay after every index change as well as array modification, I'm not sure how to make it work.
Any suggestions? I'd also appreciate some general criticism of my coding in terms of practices/conventions.
Full source is available here.
I'm somewhat new to creating games in Java, however my current setup is such that the FPS on the paint method is bounded only by the system. So, my FPS tends to be between 300 and 450. In order to standardize movement speeds on objects, I've been dividing the increment by the FPS so that it will increment that total amount in a one second time-frame.
I have the following code. What I want to do it make it so that map.addEntity() is not called 300 or 400 times per second, in accordance with the FPS; but rather make it so that I can choose, for example, to make the projectile fire at 10 RPS or so. How can I achieve this?
public void mousePressed(MouseEvent e) {
if (gameStarted)
shootProjectile = true;
}
public void paint(Graphics g) {
if (shootProjectile)
map.addEntity(new Projectile("projectile.png", x, y, 0, projectileSpeed));
}
I've been dividing the increment by the FPS
Don't do that! Use a Timer or a swingTimer to update everything at a constant rate. For example you could do something like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class Test {
public static void main(String[] args) throws InterruptedException {
Timer timer = new Timer(10,new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
updateProjectilePositions();
}
});
timer.start();
}
private static void updateProjectilePositions() {
// TODO Auto-generated method stub
}
}
Note that if you use a swing Timer, your projectile updating will happen on the swing thread. If the updating hangs, your GUI will also hang.
You also should not call map.addEntity inside paint() since paint() does one thing and one thing only: paint everything. You can get around this but mixing up the code that updates things like position with code that renders the objects will eventually bite you.
You should never use FPSs as your quantizer otherwise your game will run at different speeds on different machines and even on the same machine according to frame drops or spikes.
You can do two different things:
use a delta time between each frame update and update your game logic proportionally
use an accumulator in which you add the time delta and then you fire a logic update every fixed amount (so that you don't need to do things in proportion as your logic update will be fixed)
I'm trying to implement a countdown timer into a pre-existing public class and I have a few questions.
An overview: I want to have a timer within a program that counts down from 60 (seconds) once the program is initialized.
If the timer reaches zero, the program quits.
If the user meets certain parameters within the 60 second time frame, the timer resets to 60, presents a new set of parameters, and begins the countdown again. It should be able to do this an infinite number of times, until the user fails to meet parameters within 60 seconds.
There will also be some sort of (TBD) GUI representation of the timer, most likely either numerical countdown or JProgressBar.
I'm semi-new (~3 months) to programming, self-taught, and still learning lots (so be gentle) :)
My questions are:
What is the best way to implement this?
I'm assuming this needs to run in a thread?
Will the timer be easily configurable? (not important, just interesting)
Thanks for your help. If you need to see code, I can find some.
EDIT: Just for some clarification/context:
This is for a timed racing video game I'm working on to develop my skills as a programmer. The idea is that a player has 60 seconds to complete a lap. If the player completes a successful lap, the timer resets to 60 seconds and the track changes to be slightly more difficult. The game runs until the player is unable to complete a lap in 60 seconds due to the difficulty. The game records the number of laps as a high score, and asks to player if they would like to try again.
If I were you, I'd use:
an AtomicInteger variable which would keep the current countdown value;
a timer thread that would wake up every 1s and decrementAndGet() the variable, comparing the result to zero and terminating the app if the result is zero;
(possibly) a thread that would also wake up every 1s to repaint the GUI -- the best approach here depends on your GUI framework.
Finally, whenever you need to reset the count back to 60s, you just call set(newValue) from any thread.
The timer thread's run() method could be as simple as:
for (;;) {
if (counter.decrementAndGet() <= 0) {
// TODO: exit the app
}
Thread.sleep(1000);
}
I think it's much easier to get this right than trying to manage multiple Timer objects.
The best way to impliment timer in your application is using some sheduler frameworks like Quartz
You could use java.util.Timer to schedule an execution of a method and then cancel it if the requirements is met.
Like this:
timer = new Timer();
timer.schedule(new Task(), 60 * 1000);
And then make a class like this to handle the timerschedule:
class Task extends TimerTask {
public void run() {
System.exit(0);
}
}
If the requirements is met, then do this to stop it from executing:
timer.cancel();
If you need to update your GUI better to use SwingWorker http://en.wikipedia.org/wiki/SwingWorker
I would write something like this:
SwingWorker<String, Integer> timer = new SwingWorker<String, Integer>() {
Integer timer=60;
#Override
protected String doInBackground() throws Exception {
//update guiModel
//label.setText(timer.toString());
while(timer>0){
Thread.sleep(1000);
timer--;
}
return null;
}
#Override
public void done(){
System.exit(0);
}
};
JButton restart = new JButton(){
{
addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.cancel(true);
timer.execute();
}
});
}
};
In our class we are making a game. The user has to Guess words and stuff. I don't think info about the game is needed to answer my question/problem.
Ok so what I am trying to do is to give the user a time limit in which they have to guess the word. Something like 15 seconds. If the user does not guess the word in 15 seconds they lose a turn.
Problems:
We didn't learn how to use timers. I experiment with timers and stuff. I can get a timer to count down from 15.
I can't check the current time while waiting for the user to input a guess.
I don't know how to bypass Stdin.readString() and make the program check the time.
Thanks.
Well, you can use the Scanner class to gather input from the user.
You may want to avoid timers if you don't know what threading is yet, but if you do want to try, you might be interested looking into the TimerTask & Timer classes.
While you may already know, you can get time from the System class, like currentTimeMillis
You have a few options. As you said, your program is waiting for input and hence that thread is busy. What you can do is create a separate thread, pass your timer to that thread and have it check the timer. Perhaps something like the following:
public class TimerChecker implements Runnable {
private Timer timer;
public TimerChecker(Timer timer) { this.timer = timer; }
#Override
public void run() {
// implement logic here
}
}
Which you can have invoked in a new thread using:
Timer timer = ...
new Thread(new TimerChecker(timer)).start();
// Now you are free to perform your blocking operation in the current thread
Stdin.readString();
One way to do this is, well to a run a separate thread object for the timer... this thread shall handle the updating of the time and would then trigger a certain event when the time of the player runs out...
or more like, implementing a counter in a separate thread whose increments are triggered by time-step, in this case, in seconds, you can do this by calling sleep()..
the timer thread object shall maintain a variable which keeps track of the current time..
on the main method of your program, you shall continue to check the value of this variable, as a pre-condition of your main loop perhaps,
the idea is there i think, just a thought!
pseudocode
class Timer extends Thread{
int current_time = 0;
public void run(){
sleep(1000);
current_time += 1;
}
public void synchronized getCurTime(){
return current_time;
}
}
class Game{
public Game(){
Timer timer = new Timer();
timer.start();
while (timer.getCurTime() <16){
//get the guess of the user
//checks if it's correct
// if it is correct, output you win and break!
}
//time runs out
}
}
How about an Event driven architecture with Java eventing library?
Example of events with conditions.