【问题标题】:Editing Label from another Class (Java FX)从另一个类编辑标签 (Java FX)
【发布时间】:2018-02-13 21:37:18
【问题描述】:

我有一个问题: 我有一个简单的 Java FX 应用程序,其中有一个按钮,当我按下按钮时,一个线程任务启动,它必须每秒更改一个标签:

MyController.java

package application;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeUnit.*;
import java.util.*;
import java.text.DateFormat;


public class MyController implements Initializable{

    @FXML
    private Button myButton;
    @FXML
    private TextField myCountry;
    @FXML
    public Label myTime;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub
    }

    public void startTimeThread(ActionEvent event) {
        ScheduledThreadPoolExecutor eventPool =  new ScheduledThreadPoolExecutor(3);
        eventPool.scheduleAtFixedRate
        (new CheckSystemTime(), 0, 2, TimeUnit.SECONDS);
        myButton.setDisable(true);
    }

    public void setLabel(String text) {
        myTime.setText(text);
    }
}

Main.java 是标准的

CheckSystemTime.java

package application;
import java.util.*;
import java.text.DateFormat;


public class CheckSystemTime implements Runnable  {

    //String locale;

    public CheckSystemTime(/**String location**/) {
        //this.locale = location;
    }

    public void run() {

        Date rightNow;
        DateFormat timeFormatter;
        String timeOutput;

        rightNow = new Date();
        Locale currentLocale = new Locale("de");

        timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, currentLocale);
        timeOutput = timeFormatter.format(rightNow);

        //e.g. MyController.setLabel(timeOutput); doesnt work   
    }
}

所以我的问题是,我如何能够从 CheckSystemTime 类访问 setLabel 方法? 我希望你能帮助我如何解决这个问题

【问题讨论】:

  • 在您的MyController.java 中,您使用new Main() 调用eventPool.scheduleAtFixedRate。这应该是new CheckSystemTime()

标签: java multithreading javafx


【解决方案1】:

LabelMyControllerLabeltextProperty 添加到CheckSystemTime 的构造函数中。然后你可以在CheckSystemTime 中保留一个本地引用。然后你可以在你的 run 方法中访问它。但请确保将所有与 UI 相关的调用都包含在 Platform.runLater() 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多