简体   繁体   English

在 JavaFX 中按下按钮时如何创建随机圆圈位置?

[英]How to create random circle locations when Button is pressed in JavaFX?

I'm trying to learn Java from a Udemy course and I was asked to create an assignment before moving into the following sections.我正在尝试从 Udemy 课程中学习 Java,并且在进入以下部分之前,我被要求创建一个作业。

The assignment is to write a JavaFX application that displays a circle and a button and every time said button is pressed the circle should be moved to random locations.任务是编写一个 JavaFX 应用程序,该应用程序显示一个圆圈和一个按钮,每次按下所述按钮时,圆圈应移动到随机位置。

So far I have create a code that counts how many times I have clicked the button, now I would like to move the circle along with the counting:到目前为止,我已经创建了一个代码来计算我单击按钮的次数,现在我想将圆圈与计数一起移动:

public class CircleJumper extends Application {

    // Declare Variables
    private int count;
    private Circle initCircle;
    private Button initButton;
    private Text countText;

    /*
    *
    * Write function here
    *
    */
    @Override
    public void start(Stage primaryStage){

        // Initiate Variables
        count = 0;
        initCircle = new Circle(30, -50, 30);
        initButton = new Button("Click Me!");
        countText = new Text("Clicks: 0");
        // Here its where I built the click counter
        initButton.setOnAction((event) -> {
            count++;
            countText.setText("Pushes: " + count);
        });        
        ;
        Group baseDemo = new Group(initButton, countText);

        FlowPane pane = new FlowPane(baseDemo, initCircle);
        pane.setAlignment(Pos.CENTER);
        pane.setHgap(20);
        pane.setStyle("-fx-background-color: cyan");

        Scene scene = new Scene(pane, 600, 300);

        primaryStage.setTitle("Draw a Circle when Button is Pressed");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        launch(args);
    }

}

UPDATE: I decided to declare my variable count to be = Math.random();更新:我决定将我的变量计数声明为 = Math.random(); and created a circle.并创建了一个圆圈。 After that, the click of the button should get the generated Math.random and put it inside the setTranslate, am I right?之后,单击按钮应该会获取生成的 Math.random 并将其放入 setTranslate 中,对吗?

    public void start(Stage primaryStage){

        // Initiate Variables
        count = Math.random();
        initCircle = new Circle(30, 50, 30);
        initButton = new Button("Click Me!");

        Group circlePos = new Group(initCircle);
        circlePos.setTranslateX(10);
        circlePos.setTranslateY(10);

        initButton.setOnAction((event) -> {
            count++;
            circlePos.setTranslateY(count);
            circlePos.setTranslateX(count);
        });

        Group baseDemo = new Group(initButton);

        FlowPane pane = new FlowPane(baseDemo, initCircle);
        pane.setAlignment(Pos.CENTER);
        pane.setHgap(20);
        pane.setStyle("-fx-background-color: cyan");

        Scene scene = new Scene(pane, 600, 300);

        primaryStage.setTitle("Draw a Circle when Button is Pressed");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

Try it yourself first, but I'll post a solution so that you can see how it is done, in case you get stuck.首先自己尝试一下,但我会发布一个解决方案,以便您可以看到它是如何完成的,以防您遇到困难。

  1. Create a random in your application init method在您的应用程序初始化方法中创建一个随机
  2. Where you increase the click count, get a couple of ints using random.nextInt(bound) from the random.在增加点击次数的地方, 使用random.nextInt(bound)从随机数中获取几个整数
  3. Set circle centerX and centerY to your random values.将圆centerXcenterY设置为您的随机值。
  4. Done.完毕。

OK, well not quite done, the problem you will find when you try it (which you should) is that it won't work, the circle won't seem to center on the x and y values you set.好的,还没有完全完成,当你尝试它时会发现问题(你应该这样做)是它不起作用,圆圈似乎不会以你设置的 x 和 y 值为中心。 This is because the Circle is in a layout pane (FlowPane), which will ignore your manual layout settings (though not translate values).这是因为 Circle 位于布局窗格 (FlowPane) 中,它将忽略您的手动布局设置(尽管不转换值)。 The solution is to put the circle in the Group (as the first item, so that it is under everything), then put the flow pane in the group, and in the FlowPane you have your button and click counter.解决方案是将圆圈放入组中(作为第一项,使其位于所有内容下方),然后将流窗格放入组中,在 FlowPane 中您有您的按钮并单击计数器。

You might wish to reserve translateX/Y for animation not for layout, though it could be used to move shapes around and is also OK to use for that reason.您可能希望将 translateX/Y 保留为 animation 而不是布局,尽管它可以用于移动形状并且也可以因此使用。

import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.util.Random;

public class CircleJumper extends Application {
    private static final double MAX_X = 600;
    private static final double MAX_Y = 300;

    private int clickCount = 0;
    private Random random;

    @Override
    public void init() {
        random = new Random();
    }

    @Override
    public void start(Stage stage){
        Circle circle = new Circle(MAX_X / 2, MAX_Y / 2, 30);
        Button button = new Button("Click Me!");
        Text clickCountText = new Text("Clicks: " + clickCount);

        button.setOnAction((event) -> {
            clickCount++;
            clickCountText.setText("Clicks: " + clickCount);

            circle.setCenterX(random.nextInt((int) MAX_X));
            circle.setCenterY(random.nextInt((int) MAX_Y));
        });        

        Group layout = new Group(
                circle,
                new FlowPane(button, clickCountText)
        );

        stage.setScene(new Scene(layout, MAX_X, MAX_Y, Color.CYAN));
        stage.setResizable(false);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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