我正在尝试做我的第一个 GUI 应用程序,但不是全在一个类中,而是分为不同的类。这是场景之一的示例:
及以下,代码行
Button backToMainSceneButton = new Button("Return");
backToMainSceneButton.setOnAction(event -> primaryStage.setScene(scene));
Label dodajZwierzeLabel = new Label("Choose type of animal:");
ChoiceBox animalChoiceBox = new ChoiceBox();
animalChoiceBox.getItems().addAll("Dog", "Cat", "Hamster", "Degu");
HBox nameHbox = new HBox(10);
HBox massHbox = new HBox(10);
HBox healthHbox = new HBox(10);
Label nameLabel = new Label("Name: ");
TextField nameTextField = new TextField();
nameHbox.getChildren().addAll(nameLabel, nameTextField);
我想输入动物的名称及其质量,然后单击下面的“添加”按钮后,将使用文本字段中的名称和质量创建新对象“动物”。一个类很简单,但我想尝试制作更“专业”的 java 应用程序。
我有另一个类“DatebaseOfAnimals”,其中包含动物数组列表。那么我怎样才能实现类似的东西: “将名称和质量添加到文本字段”->“单击“添加”按钮”->“正在创建新对象 Animal 并将其添加到另一个类的数组列表中,并将名称和质量添加到构造函数”?
最佳答案
始终致力于发布 mcve :
import java.util.ArrayList;
import java.util.List;
public class Main {
//i assume that this initialization of DatabaseOfAnimals is
//done in the GUI class constructor. (remove static modifier)
static DatabaseOfAnimals db = new DatabaseOfAnimals();
public static void main(String[] args) {
addAnimal("Sancho", 8);//this should be executed by Add button
}
//remove static modifier
static void addAnimal(String name, float mass) {
db.addAnimal(new Animal(name, mass));
}
}
class Animal{
Animal(String name, float mass){/*do something*/}
}
class DatabaseOfAnimals{
List<Animal> list;
public DatabaseOfAnimals() {
list = new ArrayList<>();
}
void addAnimal(Animal animal) {
list.add(animal);
}
}
关于Java - 将值从 TextField 添加到另一个类的对象构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43156942/