简体   繁体   English

如何将动作列表添加到jmenuitem

[英]how to add a action listner to jmenuitem

  1. My menuitem are being added thorugh database . 我的菜单项正在通过数据库添加。
  2. i have to perform action such as opening the new jframe , if a user select a particular menuitem. 如果用户选择特定菜单项,我必须执行诸如打开新的jframe之类的操作。
  3. Here the menu dimension is add to the Menubar , and under which various menuitem are being added such as Period , Entity, which are being fetch from database. 在这里,菜单尺寸被添加到Menubar,并在其下方添加各种菜单项,例如Period,Entity,这些菜单项是从数据库中获取的。
  4. Now i want to open a new jframe on the click of Period menuitem . 现在,我想单击Period menuitem来打开一个新的jframe。

      public void MenuExp(){ JMenu DimensionMenu = new JMenu("Dimension"); JMenu editMenu = new JMenu("Help"); jMenuBar1.add(DimensionMenu); jMenuBar1.add(editMenu); //JMenuItem newAction = new JMenuItem("Account"); //fileMenu.add(newAction); //JMenuItem newPeriod = new JMenuItem("Period"); //fileMenu.add(newPeriod); try{ Class.forName("oracle.jdbc.OracleDriver"); Connection comm = (Connection)DriverManager.getConnection("jdbc:oracle:thin:@192.168.100.25:1521:orcl","SYSTEM","Admin123"); Statement st = comm.createStatement(); String Query = "select OBJECT_NAME from RAHUL_APP1.HSP_OBJECT where OBJECT_TYPE = 2 AND OBJECT_ID <> 30" ; //and User_Name ='" + jTextField1.getText()+"'"; ResultSet rs = st.executeQuery(Query); while(rs.next()){ JMenuItem newAction = new JMenuItem(rs.getString(1)); DimensionMenu.add(newAction); rs.close(); st.close(); comm.close(); newAction.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0){ System.out.println("You have clicked on the Account"); } }); } } catch(Exception e){ JOptionPane.showMessageDialog(this,e); } } 

You need to do some parametrization of the frame or have for example frame class stored also in DB and initialize it using reflexion... 您需要对框架进行一些参数化,或者将例如框架类也存储在DB中,然后使用反射将其初始化...


Update: 更新:

Implementation can be like this: 实现可以是这样的:

package betlista.so.swing.menuitemdialogsfromdb;

import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class MainFrame extends JFrame {

    public MainFrame() {
        super("Frame");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        add(createMenu());

        pack();
    }

    private JMenuBar createMenu() {
        JMenuBar menuBar = new JMenuBar();

        JMenu menu = new JMenu("Open");
        menu.add(new DialogCreatingMenuItem("Dialog 1", "betlista.so.swing.menuitemdialogsfromdb.MainFrame$MyDialog1"));
        menu.add(new DialogCreatingMenuItem("Dialog 2", "betlista.so.swing.menuitemdialogsfromdb.MainFrame$MyDialog2"));

        menuBar.add(menu);

        return menuBar;
    }

    class DialogCreatingMenuItem extends JMenuItem implements ActionListener {

        String className;

        public DialogCreatingMenuItem(String text, String className) throws HeadlessException {
            super(text);
            this.className = className;
            addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                Class<JDialog> clazz = (Class<JDialog>)Class.forName(this.className);
                JDialog dialog = clazz.newInstance();
                dialog.setVisible(true);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

    }

    public static class MyDialog1 extends JDialog {
        public MyDialog1() {
            setTitle("Dialog 1");
            add(new JLabel("Dialog 1"));
            pack();
        }
    }

    public static class MyDialog2 extends JDialog {
        public MyDialog2() {
            setTitle("Dialog 2");
            add(new JLabel("Dialog 2"));
            pack();
        }       
    }

    public static void main(String[] args) {
        new MainFrame().setVisible(true);
    }

}

where Strings in 字符串在哪里

    menu.add(new DialogCreatingMenuItem("Dialog 1", "betlista.so.swing.menuitemdialogsfromdb.MainFrame$MyDialog1"));
    menu.add(new DialogCreatingMenuItem("Dialog 2", "betlista.so.swing.menuitemdialogsfromdb.MainFrame$MyDialog2"));

are retrieved from database... 从数据库中检索...

Here is a sample code: 这是一个示例代码:

menuItem1.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    ...
                }
            });

Remember the steps to creating a menu: 1. Create a MenuBar and add to the panel 2. Create a Menu and add to MenuBar 3. Create a MenuItem and add to Menu 记住创建菜单的步骤:1.创建一个MenuBar并添加到面板2.创建一个菜单并添加到MenuBar 3.创建一个MenuItem并添加到Menu

Then add the listener to the MenuItem 然后将侦听器添加到MenuItem

Edit: if you use it outside the try statement it should work 编辑:如果在try语句之外使用它,则应该可以使用

Now i want to open a new jframe on the click of Period menuitem 现在,我想单击Period菜单项打开一个新的jframe

Of course you have to add an ActionListener to your menu to do that, but the real question is How do you determine the right listener to each menu item? 当然,您必须在菜单上添加一个ActionListener ,但是真正的问题是如何确定每个菜单项的正确监听器? Since you fetch your menu items from database then it's not that easy as it looks like. 由于您是从数据库中获取菜单项的,因此它看起来并不容易。

Note: see The Use of Multiple JFrames, Good/Bad Practice? 注意:请参见“使用多个JFrame,良好/不良做法?”


Option 1 (kind of dirty) 选项1(有点脏)

As I've said, you could store an action command and set it back to the menu item just like you set the menu's name: 就像我说过的,您可以存储一个动作命令并将其设置回菜单项,就像设置菜单名称一样:

while(rs.next()) { 
    String menuName =  rs.getString("menuname");
    String actionCommand = rs.getString("actioncommand");
    JMenuItem newAction = new JMenuItem(menuName);
    newAction.setActionCommand(actionCommand);
    DimensionMenu.add(newAction);
    ...
}

Then you can have a listener that make use of ActionEvent#getActionCommand() to decide the right action to perform and attach this listener to all your menu items: 然后,您可以拥有一个使用ActionEvent#getActionCommand()来决定要执行的正确操作的侦听器,并将此侦听器附加到所有菜单项:

class MenuActionListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent evt) {
        String actionCommand = evt.getActionCommand();
        switch (actionCommand) {
            case "OpenNewDialog": openNewDialog(); break;
            ...
        }
    }

    private void openNewDialog() {
        // implementation here
    }
}

Then: 然后:

ActionListener listener = new MenuActionListener();

while(rs.next()) { 
    String menuName =  rs.getString("menuname");
    String actionCommand = rs.getString("actioncommand");
    JMenuItem newAction = new JMenuItem(menuName);
    newAction.setActionCommand(actionCommand);
    newAction.addActionListener(listener);
    DimensionMenu.add(newAction);
    ...
}

Option 2 选项2

Implement Factory method pattern to create a specific ActionListener or Action based on menu's action command: 实现Factory方法模式以根据菜单的action命令创建特定的ActionListenerAction

class ActionListenerFactory {

    public static Action createAction(final String actionCommand) {
        switch (actionCommand) {
            case "OpenNewDialog": return openNewDialogAction(); break;
            ...
        }
    }

    private Action openNewDialogAction() {
        Action action = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                // open new dialog here
            }
        };
        return action;
    }
}

Then: 然后:

while(rs.next()) {
    String menuName =  rs.getString("menuname");
    String actionCommand = rs.getString("actioncommand");
    JMenuItem newAction = new JMenuItem(menuName);
    newAction.setActionCommand(actionCommand);
    newAction.addActionListener(ActionListenerFactory.createAction(actionCommand));
    DimensionMenu.add(newAction);
    ...
}

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM