Class 如何从类B访问类a中的对象
我有以下主要课程:Class 如何从类B访问类a中的对象,class,constructor,javafx,Class,Constructor,Javafx,我有以下主要课程: public class JavaFXApplication4 extends Application { @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Add to the list"); TextArea peopleList = new TextArea(); String name = "name";
public class JavaFXApplication4 extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Add to the list");
TextArea peopleList = new TextArea();
String name = "name";
String surname = "surname";
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Person p = new Person(name, surname);
}
});
StackPane root = new StackPane();
root.getChildren().addAll(btn, peopleList);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("People list");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
如何从其他类访问主类的元素?将这些变量设置为实例变量或类变量,因为局部变量只能在声明它们的函数内部访问 若您使用实例变量,则将它们设置为私有,并使用getter和setter访问它们
private TextArea peopleList = new TextArea();
public TextArea getPeopleList(){ // getter to access
return peopleList;
}
public void setPeopleList(TextArea peopleList){
this.peopleList=peopleList;
}
在其他类中创建MainClass的对象,并使用getter和setter使用它们
或者使它们成为主类中的静态/类变量,以便可以使用主类的名称进行访问
static TextArea peopleList = new TextArea();
在另一节课上呢
MainClass.peopleList
好的,但是如果我必须在类a中使用像
setUpGUI(){TextArea peopleList=new TextArea();}
这样的方法创建GUI呢?在需要之前不要启动变量,很简单。声明为实例或静态,并在需要时启动它们谢谢。我问是因为我在OOP教授身上看到了它。他经常创建一个设置gui方法,并将delcare对象作为“最终”对象。这似乎是一种尝试设计应用程序的奇怪方式。Person
类通常只表示数据-它不应该知道数据是如何呈现给用户的。你为什么要这样做?因为我的老师总是以一种狡猾的方式做事,以看看我们是否理解得很好。不幸的是,有时结果令人困惑。
MainClass.peopleList