【问题标题】:Using JAVAFX how would i make a label show numbers incrementing when i click a button使用 JAVAFX 如何在单击按钮时使标签显示数字递增
【发布时间】:2016-03-05 23:57:36
【问题描述】:
FeathersPerSec fps = new FeathersPerSec();
public void start(Stage primaryStage)
{
    double getFeathers = fps.getNumOfFeathers();
    //double setFeathers = fps.setNumOfFeathers(1);
    double click = 1;


    GridPane pane = new GridPane();
    Image image = new Image("dancingChicken.gif");
    Button chickenClick = new Button();

    Label  feathers  = new Label("FPS " + click);
    chickenClick.setGraphic(new ImageView(image));

    chickenClick.setOnAction((e) -> {

         click++;
          feathers  = new Label("FPS" + click);
    });

这是我的程序的一部分,我正在尝试制作一个 cookie 点击器类型的游戏。除了鸡和羽毛。我试图做到这一点,因此当用户单击图像按钮时,羽毛的数量将增加一。我不确定我应该在 setOnAction 中放什么。在我目前的设置中,我不断收到“在封闭范围内定义的局部变量羽毛必须是最终的或有效的最终结果。”

【问题讨论】:

    标签: java button javafx labels


    【解决方案1】:

    您需要更新当前标签的文本,而不是创建新标签(这不是场景图的一部分)。

    此外,您不能更改 lambda 表达式中的局部变量(在 lambda 表达式中访问的局部变量必须是最终的或实际上是最终的(意味着它们只能被赋值一次)) .最简单的解决方法是将click 移动到一个实例变量:

    private FeathersPerSec fps = new FeathersPerSec();
    private double click ;
    
    public void start(Stage primaryStage)
    {
        double getFeathers = fps.getNumOfFeathers();
        //double setFeathers = fps.setNumOfFeathers(1);
        click = 1;
    
    
        GridPane pane = new GridPane();
        Image image = new Image("dancingChicken.gif");
        Button chickenClick = new Button();
    
        Label  feathers  = new Label("FPS " + click);
        chickenClick.setGraphic(new ImageView(image));
    
        chickenClick.setOnAction((e) -> {
    
             click++;
             feathers.setText("FPS" + click);
        });
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多