【发布时间】:2014-04-28 04:05:48
【问题描述】:
我在一个主类中有两个 Action Listener 内部类。每一个都对应自己的按钮。其中一个动作侦听器被编码为生成一个数组列表。另一个只是将该数组列表写入文本字段。
我的问题是如何从其他 Action Listener 引用/访问该数据?下面的代码可以编译,但是当我从第二个 Action Listener 检查 Array List 的内容时,它是空的 ([])。
我猜这与调用其他动作侦听器的 actionPerformed 方法时重新实例化的数组列表有关。我该如何解决这个问题? (这里的代码只是 2 个动作监听器)。
// Create a Button Listener Inner Class for Input Route Button.
class InputRouteButtonHandler implements ActionListener {
List<String> routeStopList = new ArrayList<String>();
public void actionPerformed(ActionEvent event) {
String city1 = (String) cityCombo1.getSelectedItem();
String city2 = (String) cityCombo2.getSelectedItem();
if (city1.equals(city2)) {
JOptionPane.showMessageDialog(null, "Invalid route chosen. Please choose two different cities.");
} else {
routeStopList.add(city1); //Add city1 to start of array.
int dialogResult;
do {
String routeStop = JOptionPane.showInputDialog("Enter a stop between the 2 cities:");
routeStopList.add(routeStop);
dialogResult = JOptionPane.showConfirmDialog(null, "Add another stop?");
} while (dialogResult.equals(JOptionPane.YES_OPTION));
routeStopList.add(city2); //Add city2 to end of array.
System.out.println(routeStopList); //Just checking ArrayList contents
}
}
}
// Create a Button Listener Inner Class for Route Button.
class RouteButtonHandler extends InputRouteButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String city1 = (String) cityCombo1.getSelectedItem();
String city2 = (String) cityCombo2.getSelectedItem();
System.out.println(routeStopList); //Just checking ArrayList contents
if (city1.equals(city2)) {
JOptionPane.showMessageDialog(null, "Invalid route chosen. Please choose two different cities.");
} else {
for (int i = 0; i < routeStopList.size(); i++) {
String addedRoute = routeStopList.get(i);
adminPanelTextArea.append(addedRoute + "\n");
}
}
}
}
【问题讨论】: