[英]Java - adding value from TextField to object constructor of another class
I am trying to do my first GUI apllication, but not all-in-one-class, but with dividing on different classes. 我正在尝试做我的第一个GUI应用程序,但不是一流的,而是分为不同的类。 Thats example of one of scenes: 这是一个场景的例子:
and below, lines of code 以下,代码行
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);
I would like to put name of animal, its mass, and after click on "Add" button below it would create new object 'Animal' with name and mass from textfield. 我想把动物的名字,它的质量,然后点击下面的“添加”按钮,它将创建新的对象'动物',其中包含来自文本字段的名称和质量。 It's simple in one class, but i want to try make more 'proffesional' java app. 它在一个类中很简单,但我想尝试制作更多'proffesional'的Java应用程序。
I have another class "DatebaseOfAnimals" with arraylist of animals. 我有另一个类“DatebaseOfAnimals”与动物的arraylist。 So how can I implement something like: "put name and mass to textfield" -> "click 'add' button" -> "new object Animal is creating and added to arraylist in another class, with adding name and mass to constructor" ? 那么我怎么能实现类似的东西:“把名字和质量放到文本字段” - >“点击'添加'按钮” - >“新对象动物正在创建并添加到另一个类的arraylist中,为构造函数添加名称和质量”?
Always aim to post a mcve : 始终打算发布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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.