我遇到了一个问题。我不完全明白问题是什么,但是当我尝试计算它时,我一直在变得奇怪。它可以在我更改组合框值几次时起作用。但随后它开始吐出不可行的数字。错误在于此处:
private void updateTripDurationText()
{
String speed = (String)avgspeedBox.getSelectedItem();
String dist = (String)distanceText.getText();
double d = Double.parseDouble(dist);
double s = Double.parseDouble(speed);
double durationT = d/s;
String durationTime = String.format("%.1f",(Double.valueOf(durationT)));
durationText.setText(durationTime);
}
private class ComboBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
setCities(destinationBox.getSelectedIndex(),originBox.getSelectedIndex());
updateDistanceText();
updateTripDurationText();
}
}
//This is the actionlistender that triggers our actions when the radio buttons are used. Miles is selected by default however.
private class RadioButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if (event.getSource() == kilometersRadioButton)
{
distanceLabel.setText("Distance (kilometers):");
avgspeedLabel.setText("Avg. Speeg (kph): ");
setKm(true);
}
else if (event.getSource() == milesRadioButton)
{
distanceLabel.setText("Distance (miles): ");
avgspeedLabel.setText("Avg. Speeg (mph): ");
setKm(false);
}
updateDistanceText();
updateTripDurationText();
}
}
public static void main(String[] args)
{
new TripCalculator();
}
}
问题仅在于updateTripDuration。但我无法找到导致它的原因。有关更多细节。当计算两个位置之间的距离时,取平均速度并除以它的距离。但是,通过此设置,它只能执行一次或两次更改,然后关闭并保持关闭状态。