如何在Java GUI上循环数据?
private void enterData() {
numberOfCars = 10; // the maximum number of cars to be examined will be no more than 10
carRegistration = registrationField.getText(); // car registration is what users type in the registration field
carAge = Integer.parseInt((String) ageCombo.getSelectedItem()); // the age is to be selected from the combo box
boolean accident = accidentCheckBox.isSelected(); // the accident status depends on whether or not the checkbox is ticked
discount = Fee * 0.25; // declaring that the discount is 25% of the fee
textArea.setText(String.format("%10s %10s %10s %10s", "Registration", "Age", "Accident", "Fee\n")); // placing the headings of the four categories of information into text
textArea.append(String.format("--------------------------------------------\n")); // underline separates the titles of categories from the information of each car
textArea.append(String.format("%10s %10s %10s %10s", carRegistration, carAge, Accident, "$" +Fee)); // the four categories information displayed into text for each car
if(accidentCheckBox.isSelected()) // if the accident checkbox is displayed, the accident status should display as YES
Accident = "YES";
else
Accident = "NO"; // if the accident checkbox is displayed, the accident status would display as NO
if(numberOfCars > 10)
JOptionPane.showMessageDialog(this, "You have reached the limit of cars to enter"); // display error message if the number of cars exceed 10
if (carAge > 5)
Fee = 350.00; // if the car is above 5 years of age, the fee would be $350.00
if(carAge<=5)
Fee = 200.00; // if the car is under or equal to 5 years of age, the fee would be $200.00
if(accidentCheckBox.isSelected())
Fee = Fee; // if the car has been in an accident, the fee will not change
else
Fee = Fee - discount; // if the car has not been in an accident, the fee will be discounted
if(registrationField.getText().equals(""))
{
JOptionPane.showMessageDialog(this, "Please enter a car's registration"); // error message if car registration isn't entered
}
registrationField.setText(""); // reset the registration field when data is entered
ageCombo.setSelectedIndex(0); // reset the combo box to the default number selected when data is entered
accidentCheckBox.setSelected(false); // reset the check box to its default state when data is entered
registrationField.requestFocus();
} // enterData
我想循环carRegistration
、carAge
、Accident
和Fee
的文本,我的任务是输入至少10辆车的详细信息,但是在GUI上只有一行是活动的文本,如果我要输入新数据,它的文本将替换我以前输入的文本,我希望它被输入到新行
# 1 楼答案
您正在通过
textArea.setText()
覆盖文本。在循环之前只执行一次,或者在将文本设置为文本区域时创建一个布尔标志并将其设置为true,并在尝试再次设置之前在循环中每次检查它