ratRiot01:
なぜArrayListのは、このJavaFXのコントローラコードで2回印刷していますか?
例1:
List<Compute> list = new ArrayList<>(); // declared as global
@FXML
public void clickSubmit() {
int hr = Integer.parseInt(txtHours.getText());
int min = Integer.parseInt(txtminutes.getText());
Compute compute = new Compute(hr, min);
list.add(compute);
for(int x = 0; x < list.size(); x++) {
showVBox.getChildren().add(new Label(list.get(x).toString()));
list = new ArrayList<>(copyList);
}
私は、このリスト内の2つの値を持っています。第2回提出するには、最初の値も示しました。
だから私は、別のArrayListを作成し、origListのコピーを取りました。これにより、これが提出2日に2回印刷されません。
List<Compute> copyList = new ArrayList<>(); // declared as global
@FXML
public void clickSubmit() {
List<Compute> origList = new ArrayList<>();
int hr = Integer.parseInt(txtHours.getText());
int min = Integer.parseInt(txtminutes.getText());
Compute compute = new Compute(hr, min);
origList.add(compute);
for (int x = 0; x < origList.size(); x++) {
showVBox.getChildren().add(new Label(origList.get(x).toString()));
copyList = new ArrayList<>(origList); // I took it's copy
}
}
それはまた、私の例1に2回印刷されている理由しかし、私はまだ理解していない私は、例2にしてくださいしてくださいヘルプを使用した場合、時間が適切に追加されません!
@FXML
public void clickAdd() {
Duration sum = Duration.ZERO;
for(Compute duration : list) {
sum = sum.plus(duration.getDuration());
}
System.out.println(sum);
System.out.format("%d:%02d", sum.toHours(), sum.toMinutesPart());
}
スイーパー:
あなたがループを持っていることに注意clickSubmit
submitボタンがクリックされるたびので、リスト全体をループスルーされ、各項目はのVBoxに追加されます、方法。
最初の時間がclickSubmit
クリックされると、リストは一つだけの要素を持っていますので、ラベルは1つのVBoxに追加されます。2つのので、それをクリックだ二回目は、リストには、2つの要素を持っていますより多くのラベルがにVBox、すでに最初の時間を追加して1である第1の1に追加されます。
問題を参照してください?VBoxの内容は、開始時に自動的にクリアされません。clickSubmit
あなたが想定している可能性があります。
一つの解決策は、新しい項目のために、1つのラベルだけを毎回追加することです。
public void clickSubmit() {
int hr = Integer.parseInt(txtHours.getText());
int min = Integer.parseInt(txtminutes.getText());
Compute compute = new Compute(hr, min);
list.add(compute);
showVBox.getChildren().add(new Label(compute.toString()));
}
また、clear
VBoxの追加する前に、すべてのラベルを:
public void clickSubmit() {
// note this line:
showVBox.getChildren().clear();
int hr = Integer.parseInt(txtHours.getText());
int min = Integer.parseInt(txtminutes.getText());
Compute compute = new Compute(hr, min);
list.add(compute);
for(int x = 0; x < list.size(); x++) {
showVBox.getChildren().add(new Label(list.get(x).toString()));
list = new ArrayList<>(copyList);
}
}
あなたの例2「作品」リストをクリアしているので(はい、何origList= new ArrayList<>(copyList);
リストはほとんど常に空であるので、毎回行います)。