如何通过javaFX使计数器显示在应用程序中

如何通过javaFX使计数器显示在应用程序中,java,javafx,Java,Javafx,我是javaFX新手,我想编写一个简单的代码,计算一个人按下按钮的次数,并在应用程序本身上显示该次数。目前,我的代码在IDE中打印计数器,我只想了解如何将其附加到场景中(例如,我单击run,每次单击按钮,它都会打印我在工作台中单击它的次数)。我环顾了stack overflow和youtube,但最接近我想要的是在IDE中打印它。谢谢你的帮助 import javafx.application.Application; import javafx.scene.Scene; import java

我是javaFX新手,我想编写一个简单的代码,计算一个人按下按钮的次数,并在应用程序本身上显示该次数。目前,我的代码在IDE中打印计数器,我只想了解如何将其附加到场景中(例如,我单击run,每次单击按钮,它都会打印我在工作台中单击它的次数)。我环顾了stack overflow和youtube,但最接近我想要的是在IDE中打印它。谢谢你的帮助

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;


public class JavaFXTest extends Application {
    private int counter = 0;


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

    @Override
    public void start(Stage primaryStage) throws Exception {
        Stage stage = new Stage();
        stage = primaryStage;

        Pane pane = new Pane();
        pane.setPrefSize(400,400);

        Button button = new Button("Smash it!");
        HBox root = new HBox(5, pane);

        button.setOnAction(e -> {
            counter();
        });
        root.getChildren().add(button);

        Scene scene1 = new Scene(root,1000, 800, Color.AQUA);
        stage.setScene(scene1);
        stage.setTitle("ButtonSmash!");
        stage.show();


    }


    public void counter(){
        counter++;
        System.out.println(counter);

    }
}
以下是完整的代码:

package StackOverFlow;


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;


public class JavaFXTest extends Application {
private int counter = 0;
private Label label = new Label("Count: ");

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

@Override
public void start(Stage primaryStage) throws Exception {
    Stage stage = new Stage();
    stage = primaryStage;

    Pane pane = new Pane();
    pane.setPrefSize(400,400);

    Button button = new Button("Smash it!");
    HBox root = new HBox(5, pane);

    button.setOnAction(e -> {
        label.setText("Count: "+Integer.toString(counter));
        counter();
    });
    root.getChildren().add(button);
    label.relocate(0, 0); // You can put this label, wherever you want!
    root.getChildren().add(label);

    Scene scene1 = new Scene(root,1000, 800, Color.AQUA);
    stage.setScene(scene1);
    stage.setTitle("ButtonSmash!");
    stage.show();


}


public void counter(){
    counter++;
    //System.out.println(counter);

}
}
您必须制作一个标签并将其添加到窗格中; 无论何时按下按钮,都需要更改标签上的文本