ActionListeners JMenuItems - 跨类

时间:2014-12-01 22:46:10

标签: java swing actionlistener jmenu jmenuitem

我在这里对ActionListeners的尝试非常糟糕。

一旦点击JMenuItem(在MainMenu.java中),我正在尝试使用ActionListeners从另一个类(AddForm.java)中运行代码。

首先,这是代码:MainMenu.java

package carparksystem;

import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import java.awt.event.*;

public class MainMenu extends JFrame
{
public MainMenu()
{
    JMenuBar mainMenu = new JMenuBar();
    JMenu main = new JMenu("Menu");

    mainMenu.add(main);

    JMenuItem addCar = new JMenuItem("Add Car");
    addCar.setActionCommand("Add");
    main.add(addCar);
    //addCar.addActionListener();

    JMenuItem removeCar = new JMenuItem("Remove Car");
    removeCar.setActionCommand("Remove");
    main.add(removeCar);

    JMenuItem searchCars = new JMenuItem("Search Cars");
    searchCars.setActionCommand("Search");
    main.add(searchCars);

    setJMenuBar(mainMenu);

    /*
    //Add action listener for the Add Car button
    addCar.addActionListener
    (
        new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e) 
                {
                    MainMenu.windowClosed();
                }    
            }        
    );
    */
}
}

AddForm.java:

package carparksystem;

import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.JFrame;

public class AddForm extends JFrame
{
public AddForm()
{        
    JLabel regNumLabel = new JLabel("Registration Number:");
    JLabel highValLabel = new JLabel("High Value?");
    JLabel largeLabel = new JLabel("Large Vehicle?");

    JRadioButton btnYesHighVal = new JRadioButton("Yes", false);
    JRadioButton btnNoHighVal = new JRadioButton("No", true);
    JRadioButton btnYesLarge = new JRadioButton("Yes", false);
    JRadioButton btnNoLarge = new JRadioButton("No", true);

    ButtonGroup highVal = new ButtonGroup();        //allows just one radio button from the group to be selected
    highVal.add(btnYesHighVal);
    highVal.add(btnNoHighVal);

    ButtonGroup largeCar = new ButtonGroup();       //allows just one radio button from the group to be selected
    largeCar.add(btnYesLarge);
    largeCar.add(btnNoLarge);

    JTextField regNumField = new JTextField();

    JButton addCar = new JButton("   Add  ");
    JButton addCancel = new JButton("Cancel");

    GroupLayout addLayout = new GroupLayout(getContentPane());      //chosen to display components in group layout
    getContentPane().setLayout(addLayout);
    addLayout.setAutoCreateGaps(true);
    addLayout.setAutoCreateContainerGaps(true);

    addLayout.setHorizontalGroup(addLayout.createSequentialGroup()
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(regNumLabel)
            .addComponent(highValLabel)
            .addComponent(largeLabel))
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(regNumField)
            .addGroup(addLayout.createSequentialGroup()
                .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(btnYesHighVal)
                .addComponent(btnYesLarge))
            .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(btnNoHighVal)
                .addComponent(btnNoLarge))))
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(addCar)
            .addComponent(addCancel))
    );

    addLayout.setVerticalGroup(addLayout.createSequentialGroup()
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
            .addComponent(regNumLabel)
            .addComponent(regNumField)
            .addComponent(addCar))
        .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(addLayout.createSequentialGroup()
                .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(highValLabel)
                    .addComponent(btnYesHighVal)
                    .addComponent(btnNoHighVal))
                .addGroup(addLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(largeLabel)    
                    .addComponent(btnYesLarge)
                    .addComponent(btnNoLarge)))
                .addComponent(addCancel))
        );

    setSize(375, 150);
    setTitle("Add Car");
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}

在主画面上,我画了一系列形状,首先出现在画面上。并且在菜单上方将有一个JMenu与菜单中的JMenuItems添加,删除和搜索汽车。

点击这些添加删除和搜索'菜单按钮'后,它们将打开相应的表单,允许用户输入数据。

当我使用和不使用动作侦听器运行我的代码时,它会正常运行,但菜单根本不会链接。就好像他们没有意义一样?

1 个答案:

答案 0 :(得分:2)

一些基本问题:

  • 如果一个类要对另一个类产生影响,则需要引用该另一个类,以便它可以使用其所有方法。
  • 因此,如果您的MainMenu类需要更改AddForm类的状态,那么发生这种情况的一种方法是MainMenu将需要AddForm字段,更重要的是,该字段必须引用当前活动的AddForm对象。
  • 更好的程序结构是使用M-V-C或模型 - 视图 - 控制结构,其中两个视图通过共享模型连接,但这对于您的简单程序可能有点高级。如果你想遵循最佳实践,这仍然是要走的路。 This example显示了一个更简单的视图控制理念,也可以使用。
  • 对于具有多个顶级窗口的GUI而言,这通常是一个坏主意,对于Java而言,这意味着多个JFrame。如果需要使用CardLayout,最好有一个主窗口和其他可以交换的视图,或者如果需要可以在对话框窗口中显示。请查看The Use of Multiple JFrames, Good/Bad Practice?

对于一个简单的非MVC示例,您可以使用一个类调用第二个类。假设一个JPanel,它持有一个名为View1的JList,它有一个公共方法addItem(String item),它将项目添加到JList的模型中:

public class View1 extends JPanel {
   private static final String PROTOTYPE = String.format("%50s", " ");
   private DefaultListModel<String> listModel = new DefaultListModel<>();
   private JList<String> list = new JList<>(listModel);

   public View1() {
      list.setPrototypeCellValue(PROTOTYPE);
      list.setVisibleRowCount(8);
      JScrollPane scrollPane = new JScrollPane(list);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      add(scrollPane);
   }

   public void addItem(String item) {
      listModel.addElement(item);
   }
}

考虑第二个JPanel类View2,它包含一个JTextArea和一个JButton以及一个View1实例。然后,第二个类可以调用View1的addItem(...)方法:

public class View2 extends JPanel {
   private View1 view1;
   private JTextField textField = new JTextField(10);

   public View2(View1 view1) {
      Action addItemAction = new AddItemAction();
      this.view1 = view1;
      add(textField);
      add(new JButton(addItemAction));
      textField.setAction(addItemAction);
   }

   private class AddItemAction extends AbstractAction {
      public AddItemAction() {
         super("Add Item");
         putValue(MNEMONIC_KEY, KeyEvent.VK_A);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         view1.addItem(textField.getText()); // *** calls view1's method here
         textField.selectAll();
      }
   }
}

然后,您可以创建两个类,将View1传递给View2的构造函数

  View1 view1 = new View1();
  View2 view2 = new View2(view1);

然后将一个放入JFrame,另一个放入非模态JDialog并显示。例如:

import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class SimpleGuis {
   private static void createAndShowGui() {
      View1 view1 = new View1();
      View2 view2 = new View2(view1);

      JFrame frame = new JFrame("SimpleGuis");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(view1);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);

      JDialog dialog = new JDialog(frame, "View2", ModalityType.MODELESS);
      dialog.add(view2);
      dialog.pack();
      dialog.setLocationByPlatform(true);
      dialog.setVisible(true);
   }

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

class View1 extends JPanel {
   private static final String PROTOTYPE = String.format("%50s", " ");
   private DefaultListModel<String> listModel = new DefaultListModel<>();
   private JList<String> list = new JList<>(listModel);

   public View1() {
      list.setPrototypeCellValue(PROTOTYPE);
      list.setVisibleRowCount(8);
      JScrollPane scrollPane = new JScrollPane(list);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      add(scrollPane);
   }

   public void addItem(String item) {
      listModel.addElement(item);
   }
}

class View2 extends JPanel {
   private View1 view1;
   private JTextField textField = new JTextField(10);

   public View2(View1 view1) {
      Action addItemAction = new AddItemAction();
      this.view1 = view1;
      add(textField);
      add(new JButton(addItemAction));
      textField.setAction(addItemAction);
   }

   private class AddItemAction extends AbstractAction {
      public AddItemAction() {
         super("Add Item");
         putValue(MNEMONIC_KEY, KeyEvent.VK_A);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         view1.addItem(textField.getText());
         textField.selectAll();
      }
   }
}