如何获取值并将其从一个类传递到另一个类? [英] How to get and pass a value from a class to another?
本文介绍了如何获取值并将其从一个类传递到另一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建TextField
以获取用户名.我创建了一个用于包含UI组件的新类.
I'm trying to create a TextField
to get a users name. I've created a new class for containing UI components.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class start extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Label label = new Label("Name:");
TextField textField = new TextField();
HBox hBox = new HBox();
hBox.getChildren().addAll(label,textField);
hBox.setSpacing(10);
Scene scene = new Scene(hBox,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("Hello");
primaryStage.show();
}
}
我想获得在"Hello"窗口中输入的名称,以便在另一个类ShowOff
中使用它.
I want to get the name entered in the "Hello" window to use it in another class ShowOff
.
ShowOff类
import javafx.application.Application;
public class ShowOff {
ShowOff() {
Application.launch(start.class,"myClass");
}
public static void main(String[] args)
{
}
}
我该怎么实现?
推荐答案
您将把标签的引用传递到类中.我建议阅读此以获取更多信息.
You would pass a reference of your label into the class. I recommend reading this for more information.
但是关于您的代码.这是我的修改方式:
But in regards to your code. Here is how I would revise it:
public class Start extends Application {
public static void main(String[] args) {
Application.launch(Start.class,"myClass");
}
@Override
public void start(Stage primaryStage) throws Exception {
Label label = new Label("Name:");
TextField textField = new TextField();
HBox hBox = new HBox();
hBox.getChildren().addAll(label,textField);
hBox.setSpacing(10);
Scene scene = new Scene(hBox,300,200);
primaryStage.setScene(scene);
primaryStage.setTitle("Hello");
primaryStage.show();
textField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
//Handle the change in the text value here
}
});
}
}
现在在这种情况下,我删除了您的ShowOff
类,但是如果您需要澄清,请告诉我.
Now in this case I removed your ShowOff
class but if you need some clarification let me know.
这篇关于如何获取值并将其从一个类传递到另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文