Jpopupmenu, jmenuitem, jmenu... transparent

I have extended JPopupmenu, JMenuItem, and JMenu in order to obtain some behaivier (transparent menus). Im having this prob. that the JMenu creates a normal JPopupMenu, where I would like it to use my extended JPopupMenu. I thought about overriding the method in JMenu which creates the JPopupMenu, but the JPop is private in jmenu. How to do this? I could ofcourse copy all the code of the jmenu class and just change the creation of the jpopupmenu, but that is probably illegal or something. Any ideas?
Stig.

I have the same problem.
I run my code in jdk1.3 and it works great. But in 1.4, the transparency is gone, and depeneding on the implementation, the repainting sometimes gets real crazy.

Similar Messages

  • JPopupMenu/JMenuItem sizing problem

    Hi All,
    I have a JPopupMenu that is displayed when a right-click takes place. The popup menu should display three JMenuItems when a vertex is right-clicked and one menu item when an edge is right-clicked. However, when I right-click a vertex, only two menu items are visible, and when I right-click an edge, zero menu items are visible (the popup menu appears, but it is so small that I can't see the menu item).
    Here is the relevant code:
              protected void handlePopup(MouseEvent me) {
                final VisualizationViewer vv = (VisualizationViewer)me.getSource();
                Point2D p = vv.inverseViewTransform(me.getPoint());
                PickSupport pickSupport = vv.getPickSupport();
                if(pickSupport != null) {
                    Vertex v = pickSupport.getVertex(p.getX(), p.getY());
                    Edge e = pickSupport.getEdge(p.getX(), p.getY());
                    if((v != null) && (v instanceof BrokerVertex)) {                 
                         JPopupMenu popup = new JPopupMenu();
                        JMenuItem m_SetAdvMenuItem = new JMenuItem(MonitorResources.M_SET_ADV);
                        m_SetAdvMenuItem.addActionListener(m_MonitorFrame);
                        popup.add(m_SetAdvMenuItem);
                        JMenuItem m_centerVertex = new JMenuItem("Center Vertex");
                        m_centerVertex.setAction(new CenterAction(m_graph.getLayout().getLocation(v)));
                        popup.add(m_centerVertex);
                        JMenuItem m_SetSubMenuItem = new JMenuItem(MonitorResources.M_SET_SUB);
                        m_SetSubMenuItem.addActionListener(m_MonitorFrame);
                        popup.add(m_SetSubMenuItem);
                        popup.show(vv, me.getX(), me.getY());
                        popup.pack();
                    } else if ((e != null) && (e instanceof MonitorEdge)) {
                         MonitorEdge mEdge = (MonitorEdge) e;
                         JPopupMenu popup = new JPopupMenu();
                         boolean activationCountDisplayStatus = mEdge.activationCountIsDisplayed();
                         String activationCountToggleMessage;
                         if (activationCountDisplayStatus) {
                              activationCountToggleMessage = "Hide Message Counter";
                         } else {
                              activationCountToggleMessage = "Show Message Counter";
                        JMenuItem m_activationCountMenuItem = new JMenuItem(activationCountToggleMessage);
                        m_activationCountMenuItem.setAction(new ToggleEdgeActivationCountMessageAction(mEdge));
                        popup.add(m_activationCountMenuItem);
                        popup.show(vv, me.getX(), me.getY());
                        popup.pack();
              }The problem is with the JMenuItems that use setAction instead of addActionListener (m_centerVertex and m_activationCountMenuItem). These two JMenuItems are in the popup menu list, but the popup menu is not large enough for me to see the labels given to m_centerVertex and m_activationCountMenuItem.
    Anyone know what I'm doing wrong?
    m_SetAdvMenuItem and m_SetSubMenuItem display correctly. It's as if the height of m_centerVertex and m_activationCountMenuItem are set at a value of 0 but the heights of the other two JMenuItems are the correct height.
    Message was edited by:
    themiddle

    Did you set a name value in your Actions? The name value will be used to set the text. If its null that may account for the small size of the menu item.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • JPopupMenu & JMenu conflicts

    Basically, if I do the following...
    JMenu fileMenu = new JMenu("File");
    JPopupMenu popupMenu = new JPopupMenu();
    JMenuItem quitItem = new JMenuItem("Quit");
    fileMenu.add(quitItem);
    popupMenu.add(quitItem);The quitItem only appears under the popupMenu and not in the fileMenu. However, if I do...
    JMenu fileMenu = new JMenu("File");
    JMenuItem quitItem = new JMenuItem("Quit");
    fileMenu.add(quitItem);
    JPopupMenu popupMenu = new JPopupMenu();
    quitItem = new JMenuItem("Quit");
    popupMenu.add(quitItem);Then both menus will show quitItem. However, if I change the settings on the quitItem, it will only change it for the popupMenu's quitItem (probably because it was the most recently added quitItem) but not for the fileMenu's quitItem.
    Is there a way to have both menus show the SAME quitItem without having to make two quitItem objects? Thanks in advance.

    You can't share JMenuItem, but you can use JMenu's underlying JPopupMenu as the popup menu for other components:
    component.setComponentPopupMenu(menu.getPopupMenu());There's one trick, though: you have to set popup menu's invoker back to menu after it's displayed as a component popup menu. Otherwise clicking the menu won't show the popup menu again. You can do it in a popup menu listener:
    JPopupMenu popup = menu.getPopupMenu();
    popup.addPopupMenuListener(new PopupMenuListener() {
        public void popupMenuCanceled(PopupMenuEvent e) {}
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            popup.setInvoker(menu);
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}
    });I've only tried this in JDK6, as it depends on JPopupMenu.menuSelectionChanged's implementation.
    Edited by: geoffreyzheng on Mar 19, 2008 1:15 PM
    Edited by: geoffreyzheng on Mar 19, 2008 1:16 PM

  • MouseEvents on JPopupMenu and JMenuItem

    Hi
    I am trying to get the mouse events from JPopupMenu
    and JMenuItem , but nothing happens
    I display the popup once a button is pressed , the popup is displayed but once I click it there is no response
    can some one help
    I am attaching the code
    import javax.swing.*;
    import java.awt.event.*;
    public class Pop extends JFrame implements ActionListener{
         JPopupMenu popup = new JPopupMenu();
         JMenuItem item = new JMenuItem("one");
         JMenuItem item2 = new JMenuItem("two");
         JButton ok = new JButton("ok");
         Pop(){
              H hand = new H();
              popup.add(item);
              popup.add(item2);
              popup.addMouseListener(hand);
              item.addMouseListener(hand);
              item2.addMouseListener(hand);
              ok.addActionListener(this);
              getContentPane().add(ok);
              setSize(300,300);
              show();
         public void actionPerformed(ActionEvent ee){
              popup.show(ok , 5,5);
         public static void main(String[] args){
              new Pop();
         class H extends MouseAdapter{
              public void mouseClicked (MouseEvent e){
                   JOptionPane.showMessageDialog(null,e.toString());
    }

    If you are just trying to get something done when a menuitem is clicked, then you can try to use actionListener instead of the mouselistener. Try the following:
    ActionListener al = new ActionListener()
    public void actionPerformed()
    OptionPane.showMessageDialog(null,e.toString());
    item.addActionListener(al);
    item2.addActionListener(al2);
    Now when you click an item, the dialog box would be shown.

  • JMenuItem and JPopupMenu

    Is there an esay why round this issue?
    I've got a JMenuItem that I would like to add to MULTIPLE menu's.
    when I add the JMenuItem to a "new" JPopup it dissappears from the previous one.
    eg
    JPopupMenu menu1 = new JPopupMenu();
    JPopupMenu menu2 = new JPopupMenu();
    JMenuItem disappearingItem = new JMenuItem("I'll only appear once");
    menu1.add(disappearingItem);
    menu2.add(disappearingItem);I know I could "just" create a new JMenuItem that is the same, but this seems like a hassle. Why can't I have the same JMenuItem appearing in different menus?
    Thanks,
    Steve

    Hello,
    I think its to avoid incosistency.
    This is the responsible source-code from java.awt.Container:
    /* Reparent the component and tidy up the tree's state. */
             if (comp.parent != null) {
              comp.parent.remove(comp);
                        if (index > ncomponents) {
                            throw new IllegalArgumentException("illegal component position");
                }Ragards,
    Tim

  • Why all JMenuItem's of JPopupMenu perform the same action?

    Why all JMenuItem's of JPopupMenu perform the same action?
    I trying to do something similar to what there is in JBuilder where you right click a method or a class - you get a popUpMenu and if you choose the
    "Browse Symbol" JBuilder browses to that method/class.
    I'm trying to do the same and to browse to some class of mine (not a java class). But there's a problem.
    This is my code : -
    OMClass desiredClass = event.getNavigationClass();
    if(desiredClass instanceof OMComplexClass) {
    Set classSet = desiredClass.getSimpleClasses();
    JPopupMenu menu = new JPopupMenu();
    JMenuItem menuItem = null;
    menu.add("Browse to :");
    menu.addSeparator();
    Iterator it = classSet.iterator();
    for(; it.hasNext(); ) {
    OMConcept concept = (OMConcept)it.next();
    menuItem = new JMenuItem(concept.getName());
    menuItem.addActionListener(new NavigateToComplexClass(concept));
    menu.add(menuItem);
    menu.show((JComponent)(event.getMouseEvent().getSource()), getX(), event.getMouseEvent().getY());
    ComplexClass is build of SimpleClasses - so if I want to browse to complex class I ask the user by a JPopupMenu what specific SimpleClass he would like to browse to. My ActionListener is a NavigateToComplexClass class - and hewe is the code : -
    public class NavigateToComplexClass implements ActionListener, ItemListener {
    private static OMClass classToShow = null;
    GUI_Location currentLocation = null;
    public NavigateToComplexClass(OMConcept desiredClass) {
    classToShow = (OMClass)desiredClass;
    public void actionPerformed(ActionEvent evt) {
    currentLocation = frame.fillGUI_Location();
    frame.getProject().getHistoryManager().updateHistory(currentLocation);
    if(classToShow == null) {
    return;
    frame.getClassDisplay().getTabbedPane().setSelectedIndex(1);// 1 - parameeter : Property tab.
    frame.getConceptViewPanel().selectConcept((OMConcept)classToShow);
    public void itemStateChanged(ItemEvent e) {
    The problem is that no matter what JMenuItem I select and press it's navigating to the same simpleClass like if I have a
    b
    c
    no matter what I'll press I'll always goto a (or b or c but always the same)

    hi,
    for your actionlistener all those items are more or less the same. when browsing to them you have to give them different names or better different actioncommands.
    regards

  • JPopupMenu showing only last JMenuItem

    Hello,
    I have a strange problem with JPopupMenu - only 1 JMenuItem (last one) is shown in the menu although there are 2 of them there.
    Menu is created by following sequence:
    JPopupMenu popup = new JPopupMenu;
    JMenuItem item1 = new JMenuItem();
    item.setText( "ft" );
    popup.add( item1 );
    JMenuItem item2 = new JMenuItem();
    item.setText( "m" );
    popup.add( item2 );
    Menu is activated (shown) after a button is pressed in the code called from button ActionListener:
    // parameter is ActionEvent aEvent
    popup.show( ( Component ) aEvent.getSource(), 0, 0 );
    popup.pack(); // does not affect the behaviour, if omitted
    // dubugging: trying to make sure menu has more than 1 element           
    MenuElement[] elems = popup.getSubElements();
    for( MenuElement elem: elems )
    System.out.println( elem );
    The code works, menu appears, but only with last item.
    The debug printout shows, that menu has 2 elements:
    javax.swing.JMenuItem[,0,0,0x0,layout=java.awt.BorderLayout,alignmentX=0.0,align
    mentY=0.0,border=javax.swing.plaf.metal.MetalBorders$MenuItemBorder@3b1f38,flags
    =264,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disable
    dSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,ri
    ght=2],paintBorder=true,paintFocus=false,pressedIcon=,rolloverEnabled=false,roll
    overIcon=,rolloverSelectedIcon=,selectedIcon=,text=ft]
    javax.swing.JMenuItem[,1,3,39x20,layout=java.awt.BorderLayout,alignmentX=0.0,ali
    gnmentY=0.0,border=javax.swing.plaf.metal.MetalBorders$MenuItemBorder@3b1f38,fla
    gs=264,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disab
    ledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,
    right=2],paintBorder=true,paintFocus=false,pressedIcon=,rolloverEnabled=false,ro
    lloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=m]
    Do you have an idea, why just last item is shown ?
    When I changed
    popup.show( ( Component ) aEvent.getSource(), 0, 0 );
    to
    popup.show( mainFrame, 0, 0 );
    the menu appeared in the new location, but on change of behaviour ( my first idea was, that menu is clipped to the size of button).
    Thanks.
    Martin

    Don't show us bits and pieces of code. Show us a demo program of how you are creating and attempting to show the popup menu. The code you post may not be related to the problem.
    Also, don't forget to use the "formatting tags" so the code retains its original formatting.

  • Is it possible to change the default border on a JMenu?

    Hello,
    I'm working on an application that has a simple menu system. Clicking a button opens a JPopupMenu, which contains JMenu and JMenuItem objects. I want to change the border on the JPopupMenu and its JMenu submenus to a simple line border. Calling setBorder on the JPopupMenu works just fine, but calling it on JMenu doesn't change the border. The following code illustrates my point.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MenuTest {
       JFrame f;
       JPanel p;
       JPopupMenu popup;
       JMenu mainMenu;
       JMenu subMenu;
       JButton showPopupButton;
       public MenuTest()
          f = new JFrame("Popup Menu Test");
          p = new JPanel();
          popup = new JPopupMenu();
          subMenu = new JMenu("Submenu");
          mainMenu = new JMenu("Main Menu");
          JMenuItem m;
          for (int i=0; i < 3; i++) {
             m = new JMenuItem("Submenu item " + i);
             subMenu.add(m);
          // This doesn't work.  The border remains set to the default Windows bevel.
          subMenu.setBorder(BorderFactory.createLineBorder(Color.BLACK));
          popup.add(subMenu);
          for (int i=0; i < 5; i++) {
             m = new JMenuItem("Main menu item " + i);
             popup.add(m);
          showPopupButton = new JButton("Show Popup");
          showPopupButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e)
                Component c = (Component) e.getSource();
                popup.show(c, 0, c.getHeight());
          p.add(showPopupButton);
          // This works.  It sets the border of the popup menu to a black line border.
          popup.setBorder(BorderFactory.createLineBorder(Color.BLACK));
          f.getContentPane().add(p);
          f.setSize(400, 300);
          f.setVisible(true);
       public static void main(String[] args)
          try {
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          catch (Exception e) { }
          new MenuTest();
    }Any ideas? Do I have to extend JMenu and do some custom painting to accomplish this? I'd also like to change the roll-over color on the menu items, but neither JMenu nor JPopupMenu seem to support that. It looks like borders and rollover colors are L&F dependent.
    Thanks in advance for any help.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Example {
        public static void main(String[] args)  throws Exception {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.put("MenuItem.selectionForeground", Color.GREEN);
            UIManager.put("MenuItem.selectionBackground", Color.BLACK);
            JMenuBar mb = new JMenuBar();
            Border border = BorderFactory.createRaisedBevelBorder();
            JMenu file = new BorderedMenu("File", border);
            file.add(new JMenuItem("New"));
            file.add(new JMenuItem("Open"));
            file.add(new JMenuItem("Close"));
            JMenu edit = new BorderedMenu("Edit", border);
            edit.add(new JMenuItem("Cut"));
            edit.add(new JMenuItem("Paste"));
            edit.add(new JMenuItem("Copy"));
            mb.add(file);
            mb.add(edit);
            JFrame f = new JFrame("Example");
            f.setJMenuBar(mb);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        static class BorderedMenu extends JMenu {
            private Border border;
            public BorderedMenu(String text, Border border) {
                super(text);
                this.border = border;
            public JPopupMenu getPopupMenu() {
                JPopupMenu p = super.getPopupMenu();
                p.setBorder(border);
                return p;
    }By the way, I find the following program handy when snooping around the UI defaults.
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class Listing {
        public static void main(String[] args) throws Exception {
            UIDefaults defs = UIManager.getLookAndFeelDefaults();
            ArrayList list = new ArrayList();
            for(Iterator i = defs.entrySet().iterator(); i.hasNext(); ) {
                Map.Entry entry = (Map.Entry) i.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                if (value instanceof Color)
                    list.add(key);
            Collections.sort(list);
            JPanel panel = new JPanel(new GridLayout(0,1));
            String lastCompName = "";
            for(int i=0; i<list.size(); ++i) {
                Object key = list.get(i);
                String text = key.toString();
                int dotIndex = text.indexOf('.');
                String compName = text.substring(0, dotIndex > 0 ? dotIndex : text.length());
                if (!compName.equals(lastCompName)) {
                    lastCompName = compName;
                    panel.add(new JLabel());
                Color color = defs.getColor(key);
                JLabel label = new JLabel(text, new ColorIcon(color), JLabel.LEFT);
                panel.add(label);
            JFrame f = new JFrame("Listing");
            f.getContentPane().add(new JScrollPane(panel));
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setSize(f.getWidth(), 600);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class ColorIcon implements Icon {
        public static final int ICON_WIDTH = 20;
        public static final int ICON_HEIGHT = 16;
        private Color color;
        public ColorIcon(Color color) {
            this.color = color;
        public int getIconWidth() {
            return ICON_WIDTH;
        public int getIconHeight() {
            return ICON_HEIGHT;
        public void paintIcon(Component c, Graphics g, int x, int y) {
            if (color != null) {
                Color old = g.getColor();
                g.setColor(color);
                g.fillRect(x, y, ICON_WIDTH, ICON_HEIGHT);
                g.setColor(Color.BLACK);
                g.drawRect(x, y, ICON_WIDTH-1, ICON_HEIGHT-1);
                g.setColor(old);
    }

  • JPopupMenu dispose

    I have a JPopupMenu as follows:
    JPopupMenu myJPM
    JMenu myJM
    JList myJL
    JScrollPane myJSP(myJL,....)
    JMenuItem myJMI
    myJM.add(myJSP);
    myJPM.add(myJM);
    myJPM.add(myJMI);
    As you see I get a popup with two selections one a menu item the other another menu that contains a scrollpane with a list.
    Upon selection of the menu item the popup disappears as it should be. But when I select from the list the popup does not go away. I can say myJPM.setVisible(false) and the popup disappears but myJSP stays.
    How do I dispose of the popup and associated scrollpane and list.
    thanks

    Vishnu,
    The example I gave above was a simplification of the actual UI I need to present.
    I need to present the user with a popup menu that has two catagories of items to choose from plus three other selections. Each catagory of items has could have over 50 choices. That's over 103 items on a popup menu. One runs out of screen realestate plus that is difficult for the user to navigate.
    So I want to put each of the two cataogies of items in a scrollpane. I could also do that in the Popup menu without an additional menu but that is not very clear from the users perspective. They would see two scrollpanes stacked on each other and then 3 other choices below. I prefer to do it how I have mentioned previously by creating a popup menu with a two menus and 3 menuitems attached. Each menu then gets a scrollpane. That way they only see the scrollpane when they need to.
    But as I mentioned this present a problem. When an item is selected from the JList in the scrollpane the popup menu nor the scrollpane go away. I can call myPopupMenu.setVisible(false) to make the popupmenu go away. (Alas I would rather call myPopupMenu.dispose() which doesn't exist.) But the scrollpane does not go away. If I call myScrollPane.setVisible(false) the scrollpane goes away but what I think is the scrollpanes view port remains.
    I hope this provides enough detail to make it more clear for you.
    Thanks
    Brad

  • Accessibilty and JPopupMenu

    I am using JAWS 6 with JDK 1.4.2_06 and Access Bridge 1.2.
    If I add Menuitems to a JMenu which is added to the menubar everything works as expected. One of the menu items is another JMenu, a sub-menu. When JAWS reads this it speaks "submenu" indicating that there is a sub-menu to the right of the current menu item. However, If I attached the exact same menuitems to a JPopupMenu,
    JAWS never speaks "submenu" so the user has no iindication that there is a sub-menu to the right.
    I've taken the attached code from "The JFC Swing Tutorial - Second Edition" and tweaked it slightly so the menubar and popup menu contain the same items.
    It seems as if the accessibility api is expecting the first set of menu items to be attached to a menu parent.
    If worked around this for now by adding another top level menu to the popupmenu to which I add the menuitems.
    Is this a Java or JAWS bug ?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * Like MenuDemo, but with popup menus added.
    public class TextFieldDemo {
    JTextArea output;
    JScrollPane scrollPane;
    String newline = "\n";
    public JMenuBar createMenuBar() {
    JMenuBar menuBar;
    JMenu menu;
    //Create the menu bar.
    menuBar = new JMenuBar();
    //Build the first menu.
    menu = new JMenu("A Menu");
    menu.setMnemonic(KeyEvent.VK_A);
    menu.getAccessibleContext().setAccessibleDescription(
    "The only menu in this program that has menu items");
    JMenuItem[] mi = createAMenu();
    for(int i=0; i < mi.length; ++i)
    menu.add(mi);
    menuBar.add(menu);
    //Build second menu in the menu bar.
    menu = new JMenu("Another Menu");
    menu.setMnemonic(KeyEvent.VK_N);
    menu.getAccessibleContext().setAccessibleDescription(
    "This menu does nothing");
    menuBar.add(menu);
    return menuBar;
    public Container createContentPane() {
    //Create the content-pane-to-be.
    JPanel contentPane = new JPanel(new BorderLayout());
    contentPane.setOpaque(true);
    //Create a scrolled text area.
    output = new JTextArea(5, 30);
    output.setEditable(false);
    scrollPane = new JScrollPane(output);
    //Add the text area to the content pane.
    contentPane.add(scrollPane, BorderLayout.CENTER);
    return contentPane;
    public void createPopupMenu() {
    JMenuItem menuItem;
    //Create the popup menu.
    JPopupMenu popup = new JPopupMenu();
    JMenuItem[] mi = createAMenu();
    for(int i=0; i < mi.length; ++i)
    popup.add(mi[i]);
    //Add listener to the text area so the popup menu can come up.
    MouseListener popupListener = new PopupListener(popup);
    output.addMouseListener(popupListener);
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("TextFieldDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create/set menu bar and content pane.
    TextFieldDemo demo = new TextFieldDemo();
    frame.setJMenuBar(demo.createMenuBar());
    frame.setContentPane(demo.createContentPane());
    //Create and set up the popup menu.
    demo.createPopupMenu();
    //Display the window.
    frame.setSize(450, 260);
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    class PopupListener extends MouseAdapter {
    JPopupMenu popup;
    PopupListener(JPopupMenu popupMenu) {
    popup = popupMenu;
    public void mousePressed(MouseEvent e) {
    maybeShowPopup(e);
    public void mouseReleased(MouseEvent e) {
    maybeShowPopup(e);
    private void maybeShowPopup(MouseEvent e) {
    if (e.isPopupTrigger()) {
    popup.show(e.getComponent(),
    e.getX(), e.getY());
    private JMenuItem[] createAMenu()
    JMenu submenu;
    JMenuItem menuItem;
    JRadioButtonMenuItem rbMenuItem;
    JCheckBoxMenuItem cbMenuItem;
    JMenuItem items[] = new JMenuItem[8];
    //a group of JMenuItems
    menuItem = new JMenuItem("A text-only menu item",
    KeyEvent.VK_T);
    //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_1, ActionEvent.ALT_MASK));
    menuItem.getAccessibleContext().setAccessibleDescription(
    "This doesn't really do anything");
    items[0]=menuItem;
    menuItem = new JMenuItem("Both text and icon");
    menuItem.setMnemonic(KeyEvent.VK_B);
    items[1]=menuItem;
    menuItem = new JMenuItem("icon only");
    menuItem.setMnemonic(KeyEvent.VK_D);
    items[2]=menuItem;
    //a group of radio button menu items
    ButtonGroup group = new ButtonGroup();
    rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
    rbMenuItem.setSelected(true);
    rbMenuItem.setMnemonic(KeyEvent.VK_R);
    group.add(rbMenuItem);
    items[3]=rbMenuItem;
    rbMenuItem = new JRadioButtonMenuItem("Another one");
    rbMenuItem.setMnemonic(KeyEvent.VK_O);
    group.add(rbMenuItem);
    items[4]=rbMenuItem;
    //a group of check box menu items
    cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
    cbMenuItem.setMnemonic(KeyEvent.VK_C);
    items[5]=cbMenuItem;
    cbMenuItem = new JCheckBoxMenuItem("Another one");
    cbMenuItem.setMnemonic(KeyEvent.VK_H);
    items[6]=cbMenuItem;
    //a submenu
    submenu = new JMenu("A submenu");
    submenu.setMnemonic(KeyEvent.VK_S);
    menuItem = new JMenuItem("An item in the submenu");
    menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_2, ActionEvent.ALT_MASK));
    submenu.add(menuItem);
    menuItem = new JMenuItem("Another item");
    submenu.add(menuItem);
    items[7]=submenu;
    return(items);

    Hi;
    I want to add chekboxes to a poupup menu ,how can I do that. I already have a submenu with names of columns ton hide and show them using chekcboxes and i want that same menu as a popup when i click in the tableheader.
    thanx

  • I want to have JMenu on a Side bar(JPanel) with sub menu.

    I want to have the JMenu on the sidebar(which is a
    JPanel placed at WEST). This JMenu shall have the sub
    menu with it. I got the JMenu on the Sidebar but when
    i take mouse over(or click) the MenuItem it is
    displaying the sub Menu. I am attaching the my code.
    Can anyone please let me know why it is not displaying
    the sub menu and what should be added to my code to
    work?
    Thanks in Advance(see below for code)
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class SideBarMenu extends JFrame {
         JMenuItem menuItem1,menuItem2;
         JMenu books, softwares, tools;
         JSeparator horizontal1, horizontal2,horizontal3;
         JPanel p1, p2;
          public static void main(String[] args) {
           SideBarMenu vAR =  new SideBarMenu();
         public SideBarMenu() {
              super("Side Bar");
              setSize(500,500);
              setLocation(150,100);
              setResizable(true);     
              Container content = getContentPane();
              p1 = new JPanel(new BorderLayout());
              p2 = new JPanel();
              p2.setLayout(new GridLayout(20,1));
              p2.setBorder(BorderFactory.createLineBorder(Color.black,1));
              books = new JMenu("Books");
              horizontal1 = new JSeparator( JSeparator.HORIZONTAL );
              softwares = new JMenu("Softwares");
              horizontal2 = new JSeparator( JSeparator.HORIZONTAL );
              tools = new JMenu("Tools");
                                    horizontal3 = new JSeparator( JSeparator.HORIZONTAL );
              //sub Menu for menu "books"     
              menuItem1 = new JMenuItem("Java");
              books.add(menuItem1);
              menuItem2 = new JMenuItem(".Net");
              books.add(menuItem2);
              //sub Menu for menu "Softwares"          
              menuItem1 = new JMenuItem("Java");
              softwares.add(menuItem1);
              menuItem2 = new JMenuItem(".Net");
              softwares.add(menuItem2);
              //sub Menu for menu "tools"          
              menuItem1 = new JMenuItem("Java");
              tools.add(menuItem1);
              menuItem2 = new JMenuItem(".Net");
              tools.add(menuItem2);
              p2.add(books);
              p2.add(horizontal1);
              p2.add(softwares);
              p2.add(horizontal2);
              p2.add(tools);
              p2.add(horizontal3);
              p1.add(p2,BorderLayout.WEST );
              content.add(p1);
              setVisible(true);
    }

    Hi Ashwin,
    I saw the above code which is approaching my requirement... Thats cool man. Taking that as reference i modified it to make it what i want. The code i have modified and which is very closer to my requirement is attached below. I have set the Windows Look and Feel, because its easy to track my problems with it. The problems am having are:
    1) When the mouse is removed from the menu its submenu is not disappearing.
    2) When i take the mouse over the menu its making the name(Books/softwares/tools) of the menu invisible.
    3) When i take the mouse over the sub menu items they are not getting highlighted, which means they are not listening
    I hope u will solve these issues for me...
    Also make the menu items work ie., just make them print when i click submenus like "Clicked books->java" and "clicked softwares->.Net" so that i get an idea of events....
    Many Thanks .
    Here we go,
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JSeparator;
    import javax.swing.UIManager;
    public class SideBarMenu4 extends JFrame
        JMenuBar menuBar;
        JPopupMenu popup = new JPopupMenu();
        JMenuItem menuItem1, menuItem2;
        JMenu books, softwares, tools;
        JLabel mainMenu = new JLabel("Main Menu");
        JMenu subMenu;
        JSeparator horizontal1, horizontal2, horizontal3;
        JPanel p1, p2;
        public static void main(String[] args)
            SideBarMenu4 vAR = new SideBarMenu4();
        public SideBarMenu4()
            super("Side Bar");
            setSize(500, 500);
            setLocation(150, 100);
            setResizable(true);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            Container content = getContentPane();
            p1 = new JPanel(new BorderLayout());
                        try {
              //MetalLookAndFeel.setCurrentTheme(new MacMetricsTheme());
                 UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");            
            } catch(Exception e) {}
            p2 = new JPanel();
            p2.setLayout(new GridLayout(30, 1));
            p2.setBorder(BorderFactory.createLineBorder(Color.black, 1));
            books = new JMenu("Books");
            horizontal1 = new JSeparator(JSeparator.HORIZONTAL);
            softwares = new JMenu("Softwares");
            horizontal2 = new JSeparator(JSeparator.HORIZONTAL);
            tools = new JMenu("Tools");
            horizontal3 = new JSeparator(JSeparator.HORIZONTAL);
            // sub Menu for menu "books"
            menuItem1 = new JMenuItem("Java");
              popup.add(menuItem1);
            //books.add(menuItem1);
            menuItem2 = new JMenuItem(".Net");
              popup.add(menuItem2);
              popup.setPopupSize(100,50);
            menuBar = new JMenuBar();
            menuBar.setLayout(new GridLayout(0, 1, 5, 5));
            books.add(popup);
              books.setComponentPopupMenu(popup);
            books.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e)
                     popup.show(books, 88, 0);
              softwares.add(popup);
              softwares.setComponentPopupMenu(popup);
            softwares.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e)
                     popup.show(softwares, 88, 0);
              tools.add(popup);
              tools.setComponentPopupMenu(popup);
            tools.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e)
                     popup.show(tools, 88, 0);
            // p2.add(menuBar);
            p2.add(books);
              p2.add(horizontal1);
              p2.add(softwares);
              p2.add(horizontal2);
              p2.add(tools);
              p2.add(horizontal3);
            p1.add(p2, BorderLayout.WEST);
            content.add(p1);
            setVisible(true);
    }

  • JPopupMenu question: Can I get the parent menuItem name?

    Hi Everyone.
    I have a popupMenu. It has a Menu called "Messages" which has subMenus. So, is it possible to get the string of the parent subMenuItem from the ActionEvent of clicking a subsubMenuItem. Example -
    Messages - a ---|--q
    - n             |---k
    - rSo, if I know that k is clicked, by e.getActionCommand(), is there anyway I can know that it is a subsubmenItem of a? If yes, please let me know. Any help will be highly appreciated.

    System.out.println(((JMenu)((JPopupMenu)((JMenuItem)ae.getSource()).getParent()).getInvoker()).getText());where 'ae' is the actionEvent

  • Problem with Alt , JMenu and Mnemonics

    I have built an application with a JMenuBar containing several JMenu's, the first of which is a File menu. All JMenus and JMenuItems have mnemonics associated with them. When I press the alt key the underlines show and focus appears to be given to the File menu (though it has not dropped down). If I then press a key, for example 'S', that is a mnemonic of the 'Save' jmenuitem in the File menu, the Save action is invoked. This should not occur because the menu has not opened yet.
    The behavior is what I'd expect had an accelerator (Alt+S) been defined for the Save menu item. But I have not defined any accelerators.
    Why does this happen and more importantly, is there a work around?

    Except for the 1st line in jbinit() it's all pretty standard stuff. Here's a snippet of the code:
    public class MainFrame extends JFrame implements ChangeListener {
    JMenuBar jMenuBar1 = new JMenuBar();
    JMenu jMenuFile = new JMenu();
    JMenuItem jMenuFileNew = new JMenuItem();
    JMenuItem jMenuFileSave = new JMenuItem();
    JMenu m_editMenu = new JMenu();
    JMenuItem m_editCutMenuItem = new JMenuItem();
    JMenuItem m_editCopyMenuItem = new JMenuItem();
    JMenuItem m_editPasteMenuItem = new JMenuItem();
    public MainFrame() {
    jbInit();
    //Component initialization
    private void jbInit() {
    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke(KeyEvent.VK_ALT, Event.ALT_MASK, false), "repaint");
    // file menu
    jMenuFile.setText("File");
    jMenuFile.setMnemonic(KeyEvent.VK_F);
    jMenuFileNew.setText("New...");
    jMenuFileNew.setMnemonic(KeyEvent.VK_N);
    jMenuFileNew.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jMenuFileNewSpecial_actionPerformed(e);
    jMenuFileSave.setText("Save");
    jMenuFileSave.setMnemonic(KeyEvent.VK_S);
    jMenuFileSave.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jMenuFileSaveSpecial_actionPerformed(e);
    jMenuFile.add(jMenuFileNew);
    jMenuFile.add(jMenuFileSave);
    // edit menu
    m_editMenu.setText("Edit");
    m_editMenu.setMnemonic(KeyEvent.VK_E);
    m_editCutMenuItem.setText("Cut");
    m_editCutMenuItem.setMnemonic(KeyEvent.VK_T);
    m_editCutMenuItem.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    editCutMenuItem_actionPerformed(e);
    m_editCopyMenuItem.setText("Copy");
    m_editCopyMenuItem.setMnemonic(KeyEvent.VK_C);
    m_editPasteMenuItem.setText("Paste");
    m_editPasteMenuItem.setMnemonic(KeyEvent.VK_P);
    m_editMenu.add(m_editCutMenuItem);
    m_editMenu.add(m_editCopyMenuItem);
    m_editMenu.add(m_editPasteMenuItem);
    jMenuBar1.add(jMenuFile);
    jMenuBar1.add(m_editMenu);
    this.setJMenuBar(jMenuBar1);
    etc...
    Pressing Alt+S invokes the action listener for the jMenuFileSave menu item. It should do nothing since there is no top level menu with a mnemonic of 'S'.

  • JMenu closes after checking/unchecking JCheckBoxMenuItems

    I added a JMenu to an existing JPopupMenu, and added a few JCheckBoxMenuItems, followed by a JButton to the JMenu. Currently, when I open the JMenu and check/uncheck a JCheckBoxMenuItem, the JMenu closes.
    So, my question is, how do I get the JPopupMenu, JMenu and all the JCheckBoxMenuItems to stay open while I click multiple JCheckBoxMenuItems? I basically want everything to stay open until I push the JButton. I believe this is possible, but I don't know how to go about it. And I need help ASAP. Thanks!

    Hi, yes actually it is urgent. I'm doing this for work and it took me two days becuz it was the weekend and I didn't have access to code.
    Anyways, I just created this SSCCE, as you had advised. As far as instructions are concerned, after launching the application, you need to right click on the JFrame and go from there. You will see that after selecting/unselecting one of the JCheckBoxMenuItems it goes behind the frame. I'm sorry if my instructions are confusing, all you need to do is right-click on the frame and you'll see what I'm talking about.
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JPopupMenu;
    import javax.swing.SwingUtilities;
    public class MyPopupTest {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              final JFrame frame = new JFrame("My Frame");
              frame.setSize(500,500);
              final JPopupMenu mainPopup = new JPopupMenu();
              final JMenu myMenu = new JMenu("My Menu");
              final JPopupMenu itemsPopupMenu = new JPopupMenu();
              JButton okButton = new JButton("OK");
              JCheckBoxMenuItem item1 = new JCheckBoxMenuItem("item1", true);
              JCheckBoxMenuItem item2 = new JCheckBoxMenuItem("item2", false);
              JCheckBoxMenuItem item3 = new JCheckBoxMenuItem("item3", false);
              frame.getContentPane().add(mainPopup);
              mainPopup.add(myMenu);
              myMenu.add(itemsPopupMenu);
              itemsPopupMenu.add(item1);
              itemsPopupMenu.add(item2);
              itemsPopupMenu.add(item3);
              itemsPopupMenu.add(okButton);
              okButton.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        itemsPopupMenu.setVisible(false);
                        myMenu.setVisible(false);
              myMenu.addMouseListener(new MouseAdapter()
                   public void mouseClicked(MouseEvent e)
                        if(SwingUtilities.isRightMouseButton(e))
                             mainPopup.setLocation(e.getPoint());
                             mainPopup.setVisible(true);
                   public void mouseEntered(MouseEvent e)
                        itemsPopupMenu.setLocation(new Point(myMenu.getLocationOnScreen().x + mainPopup.getWidth(),myMenu.getLocationOnScreen().y));
                        itemsPopupMenu.setVisible(true);
              frame.setVisible(true);  
    }

  • Adding JPopupMenu to JTable cell

    Hi,
    I am just wondering if I can add a JPopup menu to each cell in a JTable, so that a user can perform some tasks.For example , a user should be able to delete a table cell by choosing the delete menu item in the popup menu
    many thanks
    Ramesh

    Hi,
    Add JPopupmenu and add JMenuItems on that according to your requirement. Add MouseListener to your table and on mouseReleased event check whether you have clicked the right mouse. If right mouse is clicked, then show the popup menu that you have already created. I think the following code will help you.
    JPopupMenu lJPopupMenu = new JPopupMenu();
    JMenuItem lJMenuItem1 = new lJMenuItem();
    lJPopupMenu.add(lJMenuItem1);
    lJTable.addMouseListener(this);
    MouseReleased(java.awt.event.MouseEvent mouseEvent) {
    if(mouseEvent.isPopupTrigger()){
    lJPopupMenu.show(lJTable, mouseEvent.getX(), mouseEvent.getY());
    ActionPerformed of the JMenuItem, you write the code based on the requirement.

Maybe you are looking for