2017-04-01 31 views
1

我試圖做我的第一個GUI,技術成果,但不是所有功能於一身的一流的,但劃分在不同的類別。場景之一的那例如: 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); 

我想放的動物,其質量的名字,點擊後「添加」它下面的按鈕,將創建新的對象'動物'與文本字段的名稱和質量。它在一個類中很簡單,但我想嘗試製作更多'proffesional'java應用程序。

我有另一個類「DatebaseOfAnimals」與動物的數組列表。那麼,如何實現這樣的: 「把名字和質量文本框」 - >「單擊‘添加’按鈕」 - >「新對象動物是創建並添加到ArrayList的另一個類,與添加名稱和質量構造函數」 ?

+1

我相信添加BTN有一個動作偵聽器('setOnAction')。讓它執行一個方法來創建'Animal'對象。新的'Animal'對象可以通過arraylist類中的方法添加到'arraylist'中。 – c0der

+0

請參閱:http://stackoverflow.com/help/someone-answers – c0der

+0

我接受你的答案,因爲我還不能投票,有啥錯? –

回答

0

始終致力於發佈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); 
    } 
}