我试图使用按钮显示数组列表的前一个元素,但未显示预期结果,它仅返回第一个元素,即我想以表格形式在各自字段中显示的数据
public class AutoForm extends javax.swing.JFrame {
ArrayList<Car> carsList;
int counter;
public AutoForm() {
initComponents();
carsList= new ArrayList<Car>();
counter = 0;
}
private void BtnSendActionPerformed(java.awt.event.ActionEvent evt) {
String id = txtId.getText();
String brand = JcomboBrand.getSelectedItem().toString();
int doors = Integer.parseInt(SpinnerDoors.getValue().toString());
Car objCar = new Car();
objCar.setId(id);
objCar.setBrand(brand);
objCar.setDoors(doors);
carsList.add(objCar);
counter++;
JOptionPane.showMessageDialog(this, "The car was added" + counter);
}
private void BtnPreviousActionPerformed(java.awt.event.ActionEvent evt) {
for (int i = 0; i <= carsList.size(); i++) {
Car carTemp = carsList.get(i);
if (counter > 0) {
counter--;
txtId.setText(carTemp.getId());
JcomboBrand.setSelectedItem(carTemp.getBrand());
SpinnerDoors.setValue(carTemp.getDoors());
} else {
JOptionPane.showMessageDialog(this, "There are no records");
}
break;
}
}
}
答案 0 :(得分:1)
尝试以下
private void BtnPreviousActionPerformed(ActionEvent evt) {
if (counter > 0) {
counter--;
Car carTemp = carsList.get(counter);
txtId.setText(carTemp.getId());
JcomboBrand.setSelectedItem(carTemp.getBrand());
SpinnerDoors.setValue(carTemp.getDoors());
} else {
JOptionPane.showMessageDialog(this, "There are no records");
}
}
答案 1 :(得分:0)
break;
break语句使循环在第一次迭代后终止。您是要把它放在if-else块中吗?