1
  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.
  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.
  4. Now i want to open a new jframe on the click of Period menuitem .

         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);
            }   
        }
    
  • *My menuitem are being added thorugh database* Why? Is it a "customize your menu" kind of feature? On the other hand you could store a unique action command for each menu item and set it back to the menu item just like you set its text. Then create a generic action listener that perform different actions based on source's action command and attach it to each menu item. It will probably be enough but feels kind of dirty though. – dic19 Sep 09 '14 at 14:21
  • Yes it is customize menu , because the application would be connected to various table , every time the table changes the menu will change – user3135761 Sep 09 '14 at 14:34
  • 1
    @user3135761: Please have a look at [example5](http://stackoverflow.com/a/25627775/1057230), on this link. Use [Action](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) instead of `ActionListener` Hopefully it might will help somewhat. – nIcE cOw Sep 09 '14 at 17:13

3 Answers3

2

You need to do some parametrization of the frame or have for example frame class stored also in DB and initialize it using reflexion...


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...

Betlista
  • 10,327
  • 13
  • 69
  • 110
  • see i am not able to figure out how would i compare the value of the JMenuItem as it is being add from database – user3135761 Sep 09 '14 at 14:20
  • 1
    I added implementation example, of course in more sofisticated example dialog classes can be in different file, also in different project (but those have to be on classpath). – Betlista Sep 09 '14 at 18:54
1

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

Then add the listener to the MenuItem

Edit: if you use it outside the try statement it should work

Guest
  • 83
  • 2
  • 9
1

Now i want to open a new jframe on the click of Period menuitem

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? 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?


Option 1 (kind of dirty)

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:

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

Implement Factory method pattern to create a specific ActionListener or Action based on menu's action command:

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:

Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69