在我正在制作的项目中,我正在尝试用arraylist填充我的JavaFX按钮。
在下面你找到我制作7个按钮的视图类。现在在我的Model类中,我读了一个文件,在那里我将国家和大陆分成两个单独的arraylists。 arraylist“大陆”现在充满了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 :(得分:0)
Using this:
this.statement[i] = new Button(model.getContinents());
you are referencing the whole list and not just one contintent.
So what you might want to do instead, is something like this:
// 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)));