Perform action for certain amount of time JavaFX - java

I am making a game and I would like to play an intro picture for 3 seconds and then call the methods to start the game. I have tried using Thread.sleep but I know thats probably not a great way and it didnt work. Anyone know a good way to do this?
Here is my code:
ImageView intro = new ImageView(new Image("/Resources/Intro.png"));
root.getChildren().add(intro);
if (startGame) {
InitializeGame.InitGame();
InitializeGame.StartGame();
}
}
Thanks!

Use a PauseTransition. It's not clear from your code what parts you want to execute after the pause, but something like:
ImageView intro = new ImageView(new Image("/Resources/Intro.png"));
root.getChildren().add(intro);
PauseTransition pause = new PauseTransition(Duration.seconds(3));
pause.setOnFinished(e -> {
InitializeGame.InitGame();
InitializeGame.StartGame();
});
pause.play();

Related

How to put a delay between the initial ValueAnimator and the reverse repeat

I have a two line textview where I am attempting to do the following:
when data arrives, fade out the second line only
change the data presented in the second line
fade the second line back in
I am currently using the following code to accomplish this:
ValueAnimator alphaAnim = ValueAnimator.ofInt(255,0).setDuration(1000);
alphaAnim.setRepeatMode(ValueAnimator.REVERSE);
alphaAnim.setRepeatCount(1);
alphaAnim.setStartDelay(500);
alphaAnim.addUpdateListener(valueAnimator -> {
int alpha = (int) valueAnimator.getAnimatedValue();
int newColor = binding.ForegroundSpanText.getCurrentTextColor() & 0x00ffff | (alpha <<24);
SpannableString tempStringHolder = binding.getAnimString();
if(fadingSpan !=null){
tempStringHolder.removeSpan(fadingSpan);
}
fadingSpan = new ForegroundColorSpan(newColor);
tempStringHolder.setSpan(fadingSpan, tempStringHolder.toString().indexOf("\n"), tempStringHolder.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
if(Integer.toHexString(newColor).equals("1000000") && !tempStringHolder.toString().equals("This is my test text with lots of text\n and this is the new text that will animate in!!")){
animStringHolder = new SpannableString("This is my test text with lots of text\n and this is the new text that will animate in!!");
binding.setAnimString(animStringHolder);
binding.executePendingBindings();
}else{
binding.setAnimString(tempStringHolder);
}
});
The issues I am currently running into are:
The change between the initial text and the text I change to is still visible because the reverse animation happens immediately, so I am looking for a way to add a delay between the reversal. I realize that this could be done with a second animator but was hoping someone might have some idea of how to accomplish this without.
Also if anyone has a better way to set the data/check if the end point of the first animator has been reached that would be awesome, I tried to override the onAnimationEnd() function but that occurs when the entire animation finishes, meaning after the reverse repeat.
In further research I found onAnimationRepeat() which is part of AnimationListenerAdapter. So the code to make this a part of what I posted originally would look like:
alphaAnim.addListener(new AnimatorListenerAdapter(){
#Override
public void onAnimationEnd(Animator animation){
System.out.println("Finished");
}
#Override
public void onAnimationRepeat(Animator animation){
animStringHolder = new SpannableString("This is my test text with lots of text\n and this is the new text that will animate in!!");
binding.setAnimString(animStringHolder);
}
});

Trying to animate a die roll in Java

I'm attempting to "animate" a die roll in Java. I currently have an icon (called "diceImage") set up that, when a button is clicked (called "diceRoll"), updates to a new random image of a die face. What I would like to do is have it change image (to a random die face) numerous times over a couple of seconds before stopping on a final image.
The problem I have is not with generating a random number, or rolling it numerous times, it's with the updating the image numerous times within a loop. The code below, which rolls the die 10 times is what I have so far:
private void diceRollActionPerformed(java.awt.event.ActionEvent evt) {
for (int i = 1; i <= 10; i++) {
rollDice();
pause(100);
}
}
This links to the following two methods (the first of which generates the random number, and sets the icon image):
private void rollDice() {
Random r = new Random();
int randomNumber = r.nextInt(6) + 1;
diceImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Game/Images/Dice " + randomNumber + ".png")));
}
The method below is "supposed" to pause the programme briefly between updating the image (this was taken from a programming course I was on where we had to animate an image of a car moving across the screen):
private void pause(int sleepTime) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
System.exit(-1);
}
}
All this programme seems to do is pause and then print the final dice roll. It doesn't show any of the "intermediate" faces. Does anyone have any ideas on why this isn't working?
Any help is greatly appreciated.
This question is asked several times a day. If you sleep in the event dispatch thread, you're preventing it from doing its job: react to events and repaint the screen.
Your animation should be done in another thread. Read the tutorial about concurrency in Swing, and use a Swing Timer.
The pause() you are using is when u need to animate moving stuff like a car for example , but just changing the icon of a JLabel which is the dice here doesn't need pause ( unless you just want it to be delayed a bit) ...
but anyways , to solve your issue , you need to call repaint() on that JLabel or updateGraphics(). Setting the Icon for the JLabel doesn't make the new Icon get displayed , you just need to repaint() it .
of course like JB Nizet said , for the app not to hang you need to call repaint on a new Thread .Thought you have to learn how to use Thread well cuz it can be very tricky at times .
good luck

Timer loop to constantly loop series of images [Java-NetBeans]

I'm trying to create a loop using Java Swing Timer to constantly cycle through a set of images (i1, i2, i3....in where n is total number of images).
Each of the images is exactly the same size and must be displayed on a Label (say, l1).
There must be a delay of ten seconds between each image being displayed.
Any idea how I can go about this without using the Java TumbleItem applet> It's seems much too complicated for a simple implementation such as mine. (Displaying special deals posters on an online storefront application for school).
I am open to this being achieved in any other way.
Help would be greatly appreciated. Thanks in advance!
I'm trying to create a loop using Java Swing Timer to constantly cycle through a set of images
When you use a Timer you don't use a loop. When the Timer fires you just change the image. So somewhere you would need to keep a List of the images to display and an index of the currently displayed image.
Any idea how I can go about this without using the Java TumbleItem applet> It's seems much too complicated for a simple implementation such as mine
How is it complicated? It displays a series of images, which is close to what you want.
Yes, there is some extra code that loads the images and doesn't start the animation until all the images are loaded. So you could easily simplify the code by not worry about that. Also, there is code that does animation from from left-to-right and then right-to-left. You also don't need that part of the code. Also, there is code that configures the animation speed. Again you can hard code that.
So if you start with that example and then simplify the code you will have a simple solution. Give it a try and then post your code when you encounter a problem.
This is very simple. Use a timer like this:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
//codehere
}
}, 0, delayInMillis)
Use can use an integer to specify in image.
public int image = 1;
in the run() function, use this to switch between the image
if(image = 1) {
image = 2;
} else if(image = 2) {
image = 3;
} if(image = 3) {
image = 0;
}
Now, wherever you are drawing your images, use this:
if(image == 1) {
//draw first image
} else if(image == 2) {
//draw second image
} else if(image == 3) {
//draw third image
}

How can I animate multiple buttons simultaneously?

I am trying to do a Translate Animation on multiple ImageViews(Buttons) simultaneously. The TranslateAnimations however, vary for each ImageView, so I am putting them in an AnimationSet. The problem is, that somehow the animation is never even run... I don't know why. Here is my code:
ArrayList<TranslateAnimation> animlist = new ArrayList<TranslateAnimation>();
AnimationSet set = new AnimationSet(true);
//The following for-loop is actually running inside two other for loops... I'm skimming it down a little for you guys
for(int i = ROWS-1; i > row;i--){
if(!usedFields[column][i]){
ImageView iv = (ImageView)GameLayout.findViewWithTag(""+row+","+column);
TranslateAnimation transanim = new TranslateAnimation(0,0,-(i-row)*letterHeight,0);
transanim.setDuration(1000);
iv.setAnimation(transanim);
animlist.add(transanim);
break;
}
}
for (TranslateAnimation anim : animlist){
set.addAnimation(anim);
}
set.startNow();
Thank you, I appreciate it!

Android, how to make a thread sleep?

Here's my code that, upon a click of the "menu" button, slides 'menubtm' in or out of view. Is there a way to make it pause for a few milliseconds at every loop, so that it would be viable, how the menubtm moves?
Thanks!
#Override
public boolean onKeyDown(int keycode, KeyEvent event ) {
if(keycode == KeyEvent.KEYCODE_MENU){
if ( menuBtmVisable == true )
{
menuBtmVisable = false;
int xnow = menuBtmTopLimit;
while (xnow<menuBtmTopLimit+120)
{
xnow+=1;
AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(480, 120, 0, xnow);
menubtm.setLayoutParams(lp);
}
}
else
{
menuBtmVisable = true;
int xnow = menuBtmTopLimit+120;
while (xnow>menuBtmTopLimit)
{
xnow-=1;
AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(480, 120, 0, xnow);
menubtm.setLayoutParams(lp);
}
}
}
return super.onKeyDown(keycode,event);
}
EDIT:
Thanks to your advice, I did it with animations.
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0"
android:toYDelta="120"
android:duration="500"
/>
This animation has to make the menu slide 120 px down... it does so ok, but then springs back into the old place. Is there a way to make it stay in the new location?
EDIT2 : got it!
android:fillEnabled="true"
android:fillAfter="true"
Instead of hacking it yourself, use Android Animations, which is designed exactly for this sort of thing. It will be much more stable and probably look much better in the end.
To answer the title: Thread.sleep will make a thread sleep.
That said, you probably don't want to do that here. If I'm understanding your snippet, onKeyDown is being called from the UI thread. You don't want to delay the UI thread either by sleeping or by doing processing that will take a while. Instead you should start an animation and return as fast as you can. See View Animation and Property Animation in the Android Dev Guide for two ways of doing animation. (Note that the latter requires 3.x or higher.)

Categories