Reputation:
I am trying to make an image "move" around using keyboard. Repositioning the image within the scene itself. I did manage to add setOnMouseClicked() on the image and change position, but it does not seem to work with the arrow keys. Going to assume I am doing something wrong.
Here is the code:
public class DEPImageMovement extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
pane.setStyle("-fx-background-color: RED");
Image img = new Image("Images/mappy.jpg");
final double centerX = img.getWidth()/2, centerY = img.getHeight()/2;
ImageView imgw = new ImageView(img);
imgw.setX(-centerX);
imgw.setY(-centerY);
imgw.setOnKeyPressed(a ->
{
switch (a.getCode())
{
case UP: {
imgw.setY(imgw.getY()-50); System.out.println("Up"); break;}
case DOWN: {
imgw.setY(imgw.getY()+50); System.out.println("Down"); break;}
case LEFT:{
imgw.setX(imgw.getX()-50); System.out.println("Left"); break;}
case RIGHT:{
imgw.setX(imgw.getX()+50); System.out.println("Right"); break;}
default:{
System.out.println("Default"); break;}
}
});
pane.getChildren().add(imgw);
Scene scene = new Scene(pane, 250 ,250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
I want to use the arrow keys to move the image around. If any easier solutions is available, those are also more than welcome as long they solve the same problem using less or simpler code/correct syntax. I am simply playing around with it trying to learn how-to do it in a number of ways.
Upvotes: 0
Views: 36
Reputation: 45786
There's already a control which seems to provide the behavior you're after: ScrollPane
. If you don't want any scroll bars then you can set the hbarPolicy
and vbarPolicy
properties to ScrollBarPolicy.NEVER
. You may also want to consider setting the pannable
property to true
.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class App extends Application {
@Override
public void start(Stage primaryStage) {
ScrollPane root = new ScrollPane(new ImageView(/* your image */));
root.setHbarPolicy(ScrollBarPolicy.NEVER);
root.setVbarPolicy(ScrollBarPolicy.NEVER);
root.setPannable(true);
primaryStage.setScene(new Scene(root, 1000, 650));
primaryStage.show();
}
}
If you focus the ScrollPane
(e.g. by clicking on it) then the arrow keys will scroll the ImageView
horizontally/vertically. Note, however, that you won't be able to "overscroll" as your current code allows.
Upvotes: 0
Reputation:
Note: Managed to fix it, by attaching the setOnActionPressed() action to the scene and not the image itself. :-) (Silly mistake)
Still if anyone have any better ideas or other ways to solve this bring them in!
Upvotes: 0