如何向jmenuitem添加动作列表器

时间:2014-09-09 14:12:14

标签: java swing jtable jmenuitem

  1. 我的menuitem正在添加数据库。
  2. 如果用户选择特定的菜单项,我必须执行打开新jframe等操作。
  3. 此处将菜单维度添加到菜单栏,并在其下添加各种菜单项,例如期间,实体,这些都是从数据库中提取的。
  4. 现在我想点击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);
            }   
        }
    

3 个答案:

答案 0 :(得分:2)

您需要对帧进行一些参数化,或者例如将帧类存储在DB中并使用反射来初始化它...


更新

实施可以是这样的:

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);
    }

}

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

从数据库中检索...

答案 1 :(得分:1)

以下是示例代码:

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

请记住创建菜单的步骤: 1.创建一个MenuBar并添加到面板 2.创建一个菜单并添加到MenuBar 3.创建一个MenuItem并添加到菜单

然后将监听器添加到MenuItem

编辑:如果你在try语句之外使用它,它应该工作

答案 2 :(得分:1)

  

现在我想点击Period menuitem

打开一个新的jframe

当然,您必须在菜单中添加ActionListener才能执行此操作,但真正的问题是如何确定每个菜单项的正确监听器?因为您提取了数据库中的菜单项然后就不那么容易了。

注意:请参阅The Use of Multiple JFrames, Good/Bad Practice?


选项1(有点脏)

正如我所说,您可以存储一个动作命令并将其设置回菜单项,就像设置菜单名称一样:

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

然后你可以让一个使用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
    }
}

然后:

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);
    ...
}

选项2

根据菜单的操作命令实施Factory method pattern以创建特定的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;
    }
}

然后:

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);
    ...
}

另见: