这是我正在做的更大程序的一部分,用户可以通过在JTextFields中输入数据来创建Flight对象。数据存储在名为flightList的Vector中。在我的JApplet的第二个面板上,用户可以使用JComboBox - flightBox - 来选择他们创建的其中一个Flights。从JComboBox中选择Flight时,需要为选定的Flight对象调用getPrice()方法,并在下面的JLabel中显示。
private class ChoiceListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//needs to be completed
if (flightBox.getSelectedIndex() == 0)
{
//flightBox.getSelectedItem(); // returns selected object
outro.setText("The price for your flight is:");
int p = flightBox.getSelectedIndex();
Flight selectedFlight = flightList.get(p);
String selectedPrice = money.format(selectedFlight.getPrice()) + "";
fPrice.setText(selectedPrice);
}
}
我以为自己走在了正确的轨道上,我尝试了很多不同的变化,但似乎都没有。 此外,我知道航班正被添加到flightList,因为JComboBox确实显示了所有添加的航班。我认为我已经正确设置了所有标签。我只需要弄清楚如何使用flightBox从flightList中实际获取所选的Flight对象,并使用getPrice方法从中获取该价格值。
从CreatePanel类(初始化变量并将Flight对象存储到JTextFields的flightList Vector中)。
CityTime departure = new CityTime();
departure.setCity(dC);
departure.setDate(dD);
departure.setTime(dT);
CityTime arrival = new CityTime();
arrival.setCity(aC);
arrival.setDate(aD);
arrival.setTime(aT);
Flight newFlight = new Flight();
newFlight.setAirlines(air);
newFlight.setFlightNum(iNum = Integer.parseInt(num));
newFlight.setPrice(dPrc = Double.parseDouble(prc));
newFlight.setDeparture(dC, dD, dT);
newFlight.setArrival(aC, aD, aT);
flightList.add(newFlight);
来自Flight类:
public class Flight
{
// Flight constructor and all other variables/accessors/mutators are added here as well.
private double price;
public double getPrice()
{
return price;
}
}
已完成的代码:
if (flightBox.getSelectedIndex() != -1)
{
//flightBox.getSelectedItem(); // returns selected object
outro.setText("The price for your flight is:");
int p = flightBox.getSelectedIndex();
Flight selectedFlight = flightList.get(p);
String selectedPrice = money.format(selectedFlight.getPrice()) + "";
fPrice.setText(selectedPrice);
}
所有航班列表矢量都已使用元素更新。