简体   繁体   中英

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. 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.

I have another class "DatebaseOfAnimals" with arraylist of animals. 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" ?

Always aim to post a 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM