Mmmh ... You can add an ActionListener directly to MenuItem, You don't need
to use a JButton for that.

Check Java Doc:

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/MenuItem.html

This works in 1.4+ :) ...

Your class most implements ActionListener Interface

public class YourClasssWithMenuItems implements *ActionListener* {
  private JMenuItem item1;
  :
  *public void actionPerformed(ActionEvent a)* {
    if(a.getSource() == item1) { // MenuItem 1 has an action event.
      :
    }
    :
  }
  :
    item1 = new JMenuItem("Item 1");
    item.addActionListener(this);
  :

Hope that can help you :)

rgds
Viel.

On Tue, Sep 22, 2009 at 10:09 PM, javaquestion
<cplusplusquest...@gmail.com>wrote:

>
> I have code:
>
>    JMenuBar menuBar = new JMenuBar();
>
>    JMenu menu1 = new JMenu("Menu 1");
>    menuBar.add(menu);
>
>    JMenuItem item1 = new JMenuItem("Item 1");
>    menu.add(item1);
>    JMenuItem item2 = new JMenuItem("Item 2");
>    menu.add(item2);
>
>    .....
>
>    JButton button = new JButton("Action");
>     button.addActionListener(
>                new ActionListener() {
>                    public void actionPerformed(ActionEvent event) {
>                            /* Check if JMenuItem is item 1 */
>                            ......
>
>                           /* Check if JMenuItem is item 2 */
>
>                           ......
>                    }
>               });
>
>   ......
>
>    // Install the menu bar in the frame
>    frame.setJMenuBar(menuBar);
>
> When I click button I would like to know which menu item I was
> selected.  I used a variable like "int status" to keep the status
> which JMmenuItem selected.  However, I was told that using something
> like glob variable is not good idea.  Then is there any other way to
> do it?
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Java EE (J2EE) Programming with Passion!" group.
To post to this group, send email to
java-ee-j2ee-programming-with-passion@googlegroups.com
To unsubscribe from this group, send email to
java-ee-j2ee-programming-with-passion+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/java-ee-j2ee-programming-with-passion?hl=en?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to