2017-08-05 207 views
-1

我正在創建一個項目,我正在用ArrayList填充我的JavaFX按鈕。用ArrayList填充JavaFX按鈕

下面你會發現我的視圖類,我做了7個按鈕。現在在我的Model類中,我讀了一個文件,我用兩個獨立的數組列表分割了國家和大陸。陣列式「大陸」現在已經遍佈7大洲。現在我想填補每個按鈕與大陸。

問題是,按鈕只能填充一個字符串,我的getter返回一個。

是否有解決方案,所以我可以將arraylist轉換爲單獨的字符串,我可以傳遞給按鈕?

public class GameView extends BorderPane { 
private Model model; 
private Button[] statement = new Button[7]; 
private Label lbl; 

public GameView() { 
    this.initialiseNodes(); 
    this.layoutNodes(); 
} 

private void initialiseNodes() { 
    this.model = new Model(); 
    for (int i = 0; i < 7; i++) { 
     this.statement[i] = new Button(model.getContinents()); 
    } 
    this.lbl = new Label("unfinished businness"); 
} 

private void layoutNodes() { 
    this.setBottom(lbl); 
    BorderPane.setAlignment(lbl,Pos.BOTTOM_CENTER); 
    BorderPane.setMargin(lbl,new Insets(20)); 

    VBox vbox = new VBox(); 
    vbox.setPadding(new Insets(20)); 
    vbox.setSpacing(10); 
    vbox.getChildren().addAll(statement); 
    this.setCenter(vbox); 
} 
} 


public class Model { 
private List<String> countries = new ArrayList<>(); 
private List<String> continents = new ArrayList<>(); 

public void readFile() throws IOException { 
    String[] ss = new String[15]; 

    try (BufferedReader reader = new BufferedReader(new FileReader("src/game.txt"))) { 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      line = line.replaceAll("\t","\n"); 
      ss = line.split("\n"); 
      for (int i = 0; i < ss.length ; i++) { 
       if((i%2)==0){ 
        countries.add(ss[i]); 
       } else{ 
        continents.add(ss[i]); 
       } 
      } 
     } 
    } catch (IOException ex) { 
     System.out.println("No file"); 
    } 
} 


public List<String> getCountries() { 
    return this.countries; 
} 

public List<String> getContinents() { 
    return this.continents; 
} 
} 
+0

您允許任何數量的大洲,但只有7個按鍵。每個按鈕在全部大陸中應該有哪些文字? – user1803551

回答

0

使用此:

this.statement[i] = new Button(model.getContinents()); 

你引用的整個列表,而不僅僅是一個contintent。

所以,你可能想要做的,而不是什麼,是這樣的:

// At the top, instead of the Button array 
final List<Button> statement = new ArrayList<>(); 

// instead of your for loop 
continents 
     // Creates a stream of all the continents 
     .stream() 
     // Creates a new stream of the existing stream that has a maximum amount of 7 items 
     .limit(7) 
     // Adds a button for every continent in the stream 
     .forEach(continent -> statement.add(new Button(continent)));