[英]Adding text to a label from another class. Java
In my program, there are two Form
and Checked
classes. 在我的程序中,有两个
Form
和Checked
类。
In the Form
class, there is a Label
and a Button
. 在
Form
类中,有一个Label
和一个Button
。 At the click in the Button
I create an instance of the class Checked
and start its thread. 单击
Button
我创建Checked
类的实例并启动其线程。
Now, what I'm having trouble with is that I need to pass the text from the Checked
class and change the Label
value, but I have not succeeded. 现在,我遇到的麻烦是我需要传递
Checked
类中的文本并更改Label
值,但是我没有成功。
Here is my code: 这是我的代码:
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);
}
}
Checked class: 已检查的班级:
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);
}
}
}
Generically you'll want to pass reference to the MainForm
or form object that you want to update into your Checked
class so that you have access to its update methods directly. 通常,您需要将对要更新的
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() {
}
}
Pass lbVerifiedNews
into the constructor of the Checked
class and store this reference in a field. 将
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.