簡體   English   中英

Java - 將TextField中的值添加到另一個類的對象構造函數中

[英]Java - adding value from TextField to object constructor of another class

我正在嘗試做我的第一個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);

我想把動物的名字,它的質量,然后點擊下面的“添加”按鈕,它將創建新的對象'動物',其中包含來自文本字段的名稱和質量。 它在一個類中很簡單,但我想嘗試制作更多'proffesional'的Java應用程序。

我有另一個類“DatebaseOfAnimals”與動物的arraylist。 那么我怎么能實現類似的東西:“把名字和質量放到文本字段” - >“點擊'添加'按鈕” - >“新對象動物正在創建並添加到另一個類的arraylist中,為構造函數添加名稱和質量”?

始終打算發布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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM