如何从另一个ActionListener访问ActionListener中的Array List元素?

时间:2014-03-21 00:12:32

标签: java swing arraylist

我在一个主类中有两个Action Listener内部类。每个对应于它自己的按钮。其中一个动作侦听器编码为生成数组列表。另一个只是将Array List写入文本字段。

我的问题是如何从其他Action Listener中引用/访问该数据?下面的代码编译但是当我从第二个Action Listener检查数组列表的内容时,它是空的([])。

我猜这与调用其他Action Listener的actionPerformed方法时重新实例化的Array List有关。我该如何解决这个问题? (这里的代码只是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");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

你是对的,你的问题是由于你创建了两个ArrayLists,列表彼此之间没有任何关系,除了持有相同类型的对象和具有相同的名称。解决方案是创建一个由两个ActionListener类共享的Model类,并在此模型类中创建ArrayList。然后给你的ArrayList类一个setModel(Model model)方法或构造函数,并将对单个Model对象的引用传递给两个ActionListeners。


另一个考虑因素是使用单个Control类来处理侦听器类型代码,然后让Control类保存Model字段。


顺便说一句,这是危险的代码:

if (city1 == city2) {

不要使用==比较字符串。请改用equals(...)equalsIgnoreCase(...)方法。理解==检查两个对象是否相同而不是您感兴趣的。另一方面,这些方法检查两个字符串是否在同一个字符中具有相同的字符订单,这就是重要的事情。


例如,假设您有两个想要操作JList的按钮,一个想要添加文本,另一个想要清除它,那么您可以将JList的模型传递给两个按钮处理程序。示例程序可能如下所示:

import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class ShareList extends JPanel {
   private static final String PROTOTYPE_CELL_VALUE = "ABCDEFGHIJKLMNOP";
   private static final int VISIBLE_ROW_COUNT = 10;
   private JTextField textField = new JTextField(10);
   private DefaultListModel<String> listModel = new DefaultListModel<>();
   private JList<String> myList = new JList<>(listModel);

   public ShareList() {
      myList.setPrototypeCellValue(PROTOTYPE_CELL_VALUE);
      myList.setVisibleRowCount(VISIBLE_ROW_COUNT);
      myList.setFocusable(false);

      JPanel buttonPanel = new JPanel();
      AddHandler addHandler = new AddHandler(listModel, this);
      textField.addActionListener(addHandler);
      buttonPanel.add(new JButton(addHandler));
      buttonPanel.add(new JButton(new ClearHandler(listModel)));

      JPanel rightPanel = new JPanel(new BorderLayout());
      rightPanel.add(textField, BorderLayout.NORTH);
      rightPanel.add(buttonPanel, BorderLayout.CENTER);

      setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
      add(new JScrollPane(myList));
      add(rightPanel);
   }

   public String getText() {
      textField.selectAll();
      return textField.getText();
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("ShareList");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new ShareList());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }

}

@SuppressWarnings("serial")
class AddHandler extends AbstractAction {
   private DefaultListModel<String> listModel;
   private ShareList shareList;

   public AddHandler(DefaultListModel<String> listModel, ShareList shareList) {
      super("Add");
      putValue(MNEMONIC_KEY, KeyEvent.VK_A);
      this.listModel = listModel;
      this.shareList = shareList;
   }

   public void actionPerformed(ActionEvent e) {
      String text = shareList.getText();
      listModel.addElement(text);
   };
}

@SuppressWarnings("serial")
class ClearHandler extends AbstractAction {
   private DefaultListModel<String> listModel;

   public ClearHandler(DefaultListModel<String> listModel) {
      super("Clear");
      putValue(MNEMONIC_KEY, KeyEvent.VK_C);
      this.listModel = listModel;
   }

   public void actionPerformed(ActionEvent e) {
      listModel.clear();
   };
}