【问题标题】:animationtimer javafx button won't update or refreshanimationtimer javafx 按钮不会更新或刷新
【发布时间】:2018-04-23 08:00:25
【问题描述】:

我的 javafx 应用程序有问题。

它只在命令行中工作,但是在进行 javafx 设置时我遇到了问题。每次我有一个按钮时,例如单击时应该隐藏另一个按钮,它不会更新或刷新。有人告诉我,animationtimer 应该可以解决我的问题,但我的问题是如何在每次单击按钮时刷新示例?

【问题讨论】:

标签: java button javafx


【解决方案1】:

请包含Minimal, Complete, and Verifiable example,以便其他人有机会看到您代码中的实际问题。以下是您的问题“如何在每次单击按钮时更新?”的答案。


您可以使用AnimationTimer 来实现此行为,但最简单的解决方案通常是使用回调。回调是单击按钮时调用的函数,您可以编写该函数。因此,当单击按钮时,您可以做任何事情。

您可以通过调用Button.setOnAction() 函数来设置此回调。你可以通过例如一个 lambda 函数或一个 EventHandler。这是一个示例,其中两个按钮在单击时相互隐藏(如您所述):

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.Button;

public class main extends Application{

    @Override public void start(Stage primaryStage) {
        Button button1 = new Button("Button 1");
        Button button2 = new Button("Button 2");

        button1.setOnAction(event -> {
            // This code is executed when button1 is pressed
            if(button2.isVisible())
                button2.setVisible(false);
            else button2.setVisible(true);
        });

        button2.setOnAction(event -> {
            // This code is executed when button2 is pressed
            if(button1.isVisible())
                button1.setVisible(false);
            else button1.setVisible(true);
        });

        button2.setLayoutX(75);

        Group root = new Group(button1, button2);
        Scene scene = new Scene(root, 200, 150);
        primaryStage.setScene(scene);
        primaryStage.setWidth(200);
        primaryStage.setHeight(150);
        primaryStage.show();
    }

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

我建议看看the callback conceptfirst class functions. 这些都是非常有用的概念,具有多种应用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多