[英]Adding text to a label from another class. Java
在我的程序中,有两个Form
和Checked
类。
在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.