如何让我的计数器通过javaFX出现在我的应用程序中

时间:2016-06-14 16:05:15

标签: java javafx

我是javaFX的新手,我想制作一个简单的代码,计算一个人按下按钮多少次并显示应用程序本身的计数。目前我的代码在我的IDE中打印计数器,并且只想将它附加到场景中(例如,我点击运行,每次单击按钮,它会打印多少次我在工作台中点击它)。我查看了堆栈溢出和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);

    }
}

1 个答案:

答案 0 :(得分:1)

以下是完整代码:

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);

}
}

您必须制作一个标签并将其添加到您的pane.getChildren(); 无论何时按下按钮,您都需要更改该标签中的文字。