问题描述
我是javaFX的新手,我需要在标签上打印按javaFX中的按钮的次数。因此,场景由一个按钮和一个标签组成,每当我按下该按钮时,标签上的数字就会增加。我似乎不正确。任何人都有一些提示吗?
这就是我所拥有的! 公共类fråga4扩展了应用程序{
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Tryck här");
primaryStage.setWidth(300);
primaryStage.setHeight(100);
VBox root = new VBox();
Button btn = new Button("Tryck här!");
Label lbl = new Label();
btn.setonMouseClicked(e -> {
btn.getonMouseClicked();
});
root.getChildren().addAll(btn,lbl);
Scene scene = new Scene (root);
primaryStage.setScene(scene);
primaryStage.show();
}
}
解决方法
您应该创建一个变量来计算按钮的点击次数,这是一个示例:
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Tryck här");
primaryStage.setWidth(300);
primaryStage.setHeight(100);
VBox root = new VBox();
Button btn = new Button("Tryck här!");
Label lbl = new Label();
// this is the variable
int i = 0 ;
btn.setOnAction(e -> {
i++ ;
System.out.println(""+i) ;
btn.getOnMouseClicked();
});
root.getChildren().addAll(btn,lbl);
Scene scene = new Scene (root);
primaryStage.setScene(scene);
primaryStage.show();
}
}