简体   繁体   中英

how can I make my javafx code count how many times I clicked on an image?

I made this java code that displays an image in a random location on the screen and whenever I click on the image it moves to another random location. I want the code to print out "Hit" and count how many times I hit the image. for some reason it keeps returning 1.

public class Main2 extends Application {
    ImagePane root = new ImagePane();
    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(root, 500,500);
        scene.setCursor(Cursor.CROSSHAIR);
        primaryStage.setScene(scene);
        primaryStage.show();
        
    }
    
    
    
    public class Handler implements EventHandler<MouseEvent>{
        public void handle(MouseEvent e) {
            root.setPosition();
            System.out.println("Hit");
            int count = 1;
            System.out.println(count++);
        }
    }
    
    
    
    public class ImagePane extends Pane{
        ImageView o = new ImageView();
        Image image = new Image("file:head2.png");
        public ImagePane() {
            getChildren().add(o);
            o.setImage(image);
            o.setFitHeight(70);
            o.setFitWidth(70);
            o.setX(Math.random()*1080);
            o.setY(Math.random()*1080);
            o.setOnMouseClicked(new Handler());
            }
        public void setPosition() {
            o.setX(Math.random()*1080);
            o.setY(Math.random()*1080);
            o.setOnMouseClicked(new Handler());
        }
    }
    
    
    public static void main(String[] args) {
        launch(args);
    }
}

Try to move count declaration out from handle() .

public class Handler implements EventHandler<MouseEvent>{
        int count;
        public void handle(MouseEvent e) {
            root.setPosition();
            System.out.println("Hit");
            System.out.println(count++);
        }
    }

Create instance of Handler class in Main2 .

Handler handler = new Handler();

And use this instance instead of cresting new in every time.

o.setOnMouseClicked(handler);

To do this you have to create a constructor for ImagePane with handler as argument.
In other words, you need to use same instance od Handler in every place.

try this, it works for me

ImagePane root = new ImagePane();

@Override
public void start(Stage primaryStage) {

    Scene scene = new Scene(root, 900, 1000);
    scene.setCursor(Cursor.CROSSHAIR);
    primaryStage.setScene(scene);
    primaryStage.show();

}

int count = 1;

public class Handler implements EventHandler<MouseEvent> {

    public void handle(MouseEvent e) {
        root.setPosition();
        System.out.println("Hit: " + count++);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM