如何在JavaFX中的AnchorPane中移动图像?图像应该在一段时间内自行移动。到目前为止,我有:(视图是已经在AnchorPane中的ImageView)
CustomerMarketingCampaignId
在我的控制器的initialize()方法中。但是,这不起作用,因为舞台出现时图像已经移动。
答案 0 :(得分:0)
这是我根据辅导学生的想法创建的课程。
您应该使用Javafx动画。这按下按钮移动,但如果你 想要看到潜水员向右移动,只需从isRightPressed if语句中删除代码并将其放在if语句之外。另外,删除此部分:*(Math.cos(Math.toRadians(rotation)))。
import java.io.File;
import javafx.animation.AnimationTimer;
import javafx.event.EventHandler;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
/**
*
* @author blj0011
*/
public class Diver {
File diverFile;
ImageView ivDiver = new ImageView();
double rotation = 0.0;
boolean isUpPressed, isDownPressed, isLeftPressed, isRightPressed;
Diver()
{
diverFile = new File("src/img/diver.png");
if(diverFile.exists())
{
Image diverImage = new Image(diverFile.toURI().toString());
ivDiver.setImage(diverImage);
}
ivDiver.setFocusTraversable(true);
ivDiver.setOnKeyPressed(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent event) {
switch(event.getCode()) {
case UP: isUpPressed = true; break;
case DOWN: isDownPressed = true; break;
case LEFT: isLeftPressed = true; break;
case RIGHT: isRightPressed = true; break;
}
}
});
ivDiver.setOnKeyReleased(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent event) {
switch(event.getCode()) {
case UP: isUpPressed = false; break;
case DOWN: isDownPressed = false; break;
case LEFT: isLeftPressed = false; break;
case RIGHT: isRightPressed = false; break;
}
}
});
AnimationTimer timer = new AnimationTimer(){
@Override
public void handle(long now) {
if(isUpPressed){if(rotation == -360){rotation = 0;} ivDiver.setRotate(rotation+=5);}
if(isDownPressed){if(rotation == 360){rotation = 0;} ivDiver.setRotate(rotation-=5);}
if(isLeftPressed)
{
ivDiver.setX(ivDiver.getX() - 2.0 * (Math.cos(Math.toRadians(rotation))));
ivDiver.setY(ivDiver.getY() - 2.0 * (Math.sin(Math.toRadians(rotation))));
}
if(isRightPressed)
{
System.out.println("moving diver right!");
ivDiver.setX(ivDiver.getX() + 2.0 * (Math.cos(Math.toRadians(rotation))));
ivDiver.setY(ivDiver.getY() + 2.0 * (Math.sin(Math.toRadians(rotation))));
}
}
};
timer.start();
}
ImageView getDiver()
{
return ivDiver;
}
}
您的代码可能看起来像这样。
AnimationTimer timer = new AnimationTimer(){
@Override
public void handle(long now) {
System.out.println("moving diver right!");
yourImageView.setX(yourImageView.getX() + 20.0 );
//yourImageView.setY(yourImageView.getY() + 20.0 );
}
};
timer.start();