繁体   English   中英

从另一个类向标签添加文本。 Java的

[英]Adding text to a label from another class. Java

在我的程序中,有两个FormChecked类。

Form类中,有一个Label和一个Button 单击Button我创建Checked类的实例并启动其线程。

现在,我遇到的麻烦是我需要传递Checked类中的文本并更改Label值,但是我没有成功。

这是我的代码:

public class MainForm extends Application {
    protected static int intVerifiedNews = 0;
    Button btnPlay = new Button("Button");
    Label lbVerifiedNews = new Label("News: ");
    @Override
    public void start(Stage primaryStage) throws IOException {

        final BorderPane border = new BorderPane();
        final HBox hbox = addHBox();

        Scene scene = new Scene(border, 850, 500, Color.BLACK);

        btnPlay.setPrefSize(100, 24);
        btnPlay.setMinSize(24, 24);

        btnPlay.setOnAction((event) -> {
                    Checked ch = new Checked();
                    ch.start();
                }
        );

        border.setTop(hbox);
        hbox.getChildren().addAll(btnPlay, lbVerifiedNews);
        primaryStage.setScene(scene);
        primaryStage.show();

    }
    private HBox addHBox() {
        HBox hbox = new HBox();
        hbox.setPadding(new Insets(5, 0, 5, 5));
        return hbox;
    }

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

已检查的班级:

public class Checked extends Thread {


    public void run() {
        for (int i = 0; i <= 5; i++) {
    MainForm.intVerifiedNews ++;
//Here you need to pass the intVerifiedNews value to the Label 
                System.out.println(MainForm.intVerifiedNews);
        }

    }
}

通常,您需要将对要更新的MainForm或form对象的引用传递到Checked类中,以便可以直接访问其更新方法。

public class Checked implements Runnable {

   public Checked(MainForm form1) {
   // store form (or the object representing the text box directly) to update later
   }

   public void run() {
   }
}

lbVerifiedNews传递到Checked类的构造函数中,并将此引用存储在字段中。

Checked ch = new Checked(lbVerifiedNews);

public class Checked extends Thread {

    Label checkedLabelReference;
    public Checked(Label label){
        this.checkedLabelReference = label;
    }

    public void run() {
        for (int i = 0; i <= 5; i++) {
            MainForm.intVerifiedNews ++;
            //Here you need to pass the intVerifiedNews value to the Label 
            Platform.runLater(new Runnable() {
                @Override public void run() {
                    checkedLabelReference.setText(MainForm.intVerifiedNews);//update text
            }});
            System.out.println(MainForm.intVerifiedNews);
        }

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM