JMenu with no JMenuItem

Hi!
I have a JMenuBar with one JMenu (File) and its JMenuItems.
I want to add another JMenu (settings) but with no JMenuItems, so when the user clicks on settings a new window is shown.
Is this possible?

You need to add a MenuListener to the higher level menu. See attached sample working code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class MenuTest
  public static void main(String args[])
    new MenuTestFrame();
class MenuTestFrame extends JFrame implements ActionListener
  JMenuBar mb = new JMenuBar();
  JMenu file = new JMenu("File");
  JMenu edit = new JMenu("Edit");
  JMenu view = new JMenu("View");
  JMenu help = new JMenu("Help");
  JMenuItem fileOpen = new JMenuItem("Open...");
  JSeparator separator = new JSeparator();
  JMenuItem fileSaveAs = new JMenuItem("Save As...");
  JMenuItem editCut = new JMenuItem("Cut");
  JMenuItem editCopy = new JMenuItem("Copy");
  JMenuItem editPaste = new JMenuItem("Paste");
  JMenuItem helpAbout = new JMenuItem("About...");
  MenuTestFrame()
    super();
    /* Components should be added to the container's content pane */
    Container cp = getContentPane();
    /* Add menu items to menus */
    file.add(fileOpen);
    file.add(separator);
    file.add(fileSaveAs);
    edit.add(editCut);
    edit.add(editCopy);
    edit.add(editPaste);
    help.add(helpAbout);
    /* Add menus to menubar */
    mb.add(file);
    mb.add(edit);
    mb.add(view);
    mb.add(help);
    /* Set menubar */
    setJMenuBar(mb);
    /* Add the action listeners */
    fileOpen.addActionListener(this);
    fileSaveAs.addActionListener(this);
    editCut.addActionListener(this);
    editCopy.addActionListener(this);
    editPaste.addActionListener(this);
    helpAbout.addActionListener(this);
    /* Add menu listener */
    view.addMenuListener(new MenuListener() {
      public void menuCanceled(MenuEvent evt) {}
      public void menuDeselected(MenuEvent evt) {}
      public void menuSelected(MenuEvent evt)
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            JOptionPane.showMessageDialog(MenuTestFrame.this,"Menu test dialog!","Message",JOptionPane.INFORMATION_MESSAGE);
    /* Add the window listener */
    addWindowListener(new WindowAdapter()
      public void windowClosing(WindowEvent evt)
        dispose();
        System.exit(0);
    /* Size the frame */
    setSize(200,200);
    /* Center the frame */
    Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle frameDim = getBounds();
    setLocation((screenDim.width - frameDim.width) / 2,(screenDim.height - frameDim.height) / 2);
    /* Show the frame */
    setVisible(true);
  public void actionPerformed(ActionEvent evt)
    Object obj = evt.getSource();
    if (obj == fileOpen);
    else if (obj == fileSaveAs);
    else if (obj == editCut);
    else if (obj == editCopy);
    else if (obj == editPaste);
    else if (obj == helpAbout);
}

Similar Messages

  • JMenu with text and icon

    Is it possible to create a JMenu with text and an icon where only the icon brings up the menu and the text behaves like a JMenuItem? How would you do this. Right now I have a JMenuItem next to a JMenu where the JMenu only has an icon. The problem with this is it is seemingly impossible to get them as close together as I would like. Any suggestions for solving the spacing issue would be equally helpfull. Thanks.

    From your previous thread you are aware that JMenu and JMenuItem both extend AbstractButton. So, you should be able to play with the borders and margins:
    setBorder(null);
    setMargin( new Insets(0, 0, 0, 0) );

  • How to get the JMenuBar associated with a JMenuItem?

    How do I get the JMenuBar (or JFrame) associated with
    a JMenuItem?
    The JMenuItem is in a subMenu of a JMenu on the JMenuBar.

    Hi,
    JMenuBar is extending from the container class,
    When a menuItem is added to it,You can get the instance of JMenuBar by type casting the getParent method on JMenuItem
    ie..
    JMenuItem mi1 = new JMenuItem();
    JMenuBar jm = new JMenuBar();
    jm.add(mi1);
    JMenuBar jm2 = (JMenuBar) mi1.getParent();
    Hope this helps
    cheers
    Ravi

  • JPopupMenu with multiline JMenuItem ?

    Hi there.
    Is it possible to do something like the subject says, a JPopupMenu with multiline JMenuItem's, without using html? I would like to create a JMenuItem with a MultiLineLabel as the argument instead of a String. I'm trying to do this because if i add the MultiLineLabel directly to the JPopupMenu, it displays as i want, but i loose the behaviour inherent to a JMenuItem, the highlighted index, etc.. Any help would be appreciated.

    Here's a workaround:
    JPopupMenu popupMenu = new JPopupMenu();
    // Workaround to stop first menu item being selected
    JMenuItem dummyItem = popupMenu.add(new JMenuItem());
    dummyItem.setPreferredSize(new Dimension(0, 0));
    popupMenu.add("Item 1");
    popupMenu.add("Item 2");
    popupMenu.add("Item 3");
    It works for me!

  • Error in JComboBox and JMenu with JDK 1.6

    We have a Desktop application that uses JMenuBar, JMenu, and JMenuItem and JComboBox. As we use the application, is the disappearance of the menu items, ie, they are not painted and does not drop down.
    We tested with jdk1.6.0 update 17.
    We tested with jdk1.6.0 update 22.
    We tried to force the paint component among other ways to make it work, but without success!
    We would like to know if it's a bug in Swing because we know other applications that use implementations Desktop also the same problem occurs.
    We look back!
    Edited by: Rubens on May 13, 2012 10:16 PM

    Works for me. The updates you tried are rather old too. But I would first suspect your code. Adding menu items fom the wrong thread for example.

  • JMenu with RIGHT_TO_LEFT Orientation

    Hello,
    I have a JFrame contains a JMenuBar and it's menus, My application direction is RIGHT_TO_LEFT, I changed the direction of the JMenuBar, JMenu, JMenuItem, to all the Heirarchy of the menus, and I got the required GUI.
    Unfortunately, when the direction is RIGHT_TO_LEFT, and lets say you have the following menus structure:
    File -> Open
    Print -> Printer Setup
    Page Setup
    Save
    Exit
    When the orientation is RIGHT_TO_LEFT, The JMenu 'Print' expanded to left side only when you press the RIGHT arrow on the keyboard !
    I extended the JMenu and JMenuItem classes and overrides the
    'processMenuKeyEvent(MenuKeyEvent e)' method and I got the required thing, but I have the following questions:
    1. How can I determine the menu that currently have the selection or the focus.
    2. I have problems if there is nested menus as print -> Printer -> Type ....
    Is there A general solution such as I can apply it to the JFrame as an example and it will reflect it on all components that it holds ?

    Thanks for your answer.
    So there is no solution for that bug (except implementing the ComboBoxUI)?
    As I found bug is in JScrollPane that used in Popup. When a JScrollPane's orientation is set to RIGHT_TO_LEFT it scrolls to the left but it is expected that it should scroll to the right.
    Edited by: gilas on Aug 2, 2008 3:18 AM

  • How to put cut and paste in a JMenu with their corresponding  accelerators

    hi everybody.
    I'm new to swing and don't now it very well. I'm trying to put in a JMenu the cut, copy, paste options, but using key accelerators instead of key bindings. i'll be glad to receive your opinions about the pros and cons of using key bindings or accelerators, and how can i write a action performed method that makes the same as cut, or copy or paste
    menu.add(getActionByName(DefaultEditorKit.pasteAction));

    Unfortunately, when you create a menu item from an action the accelerator doesn't get set automatically, so you need to do something like:
    JMenuItem paste = new JMenuItem( getActionByName.... );
    paste.setAccelerator(....);
    menu.add( paste );
    In many cases you would want to have a paste action as a menu item and as a toolbar button. Check out the following thread to see how I use the same action on a menu and toolbar:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=275270

  • Arrow of a selected JMenu with a submenu doesnt work

    Hello,
    I've a problem with a menubar with some JMenu's and some submenu's.
    The color of the arrow of a JMenu is always black when it is selected. Even when I changed the DefaultUI settings for this component.
    Sow when I change the follow parameters the text and the arrow have the good color.
    Menu.foreground (same for MenuItem)
    but when I change the follow parameters only the color of the text will change when selected and the arrow is still black
    Menu.selectedForeground (same for MenuItem)
    Do i something wrong or is this a bug ?
    Thx in advance!

    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.

  • JMenu with clickable URL

    Hi :-)
    I have JFrame, it has JMenuItems.
    If you click on the menu, a little window with a message pop-ups.
    I can add Text and Icon on this pop-up msgbox.
    How can I add a clickable WWW Url within the Text?
    -Aykut

    by default ?
    let say I have a JMenuITem content like this
    I am a message 1: http://www.test-xyz.com
    I am a message 2: http://www.test-abc.com
    If I would click, how does it knows, which URL I have clicked on ?

  • Keeping JMenu open when JMenuItem clicked

    Hey,
    I have a JCheckBoxMenuItem and a disabled JMenuItem just below it on a JMenu. When the checkbox is enabled, i would like the disabled JMenuItem to become enabled and for the JMenu to remain open. I tried
    (JPopupMenu)checkBox.getParent().setVisible(true), but this freezes the JMenu and it won't close or highlight the menu item's my mouse is over. Any ideas? Appreciate your help.
    -kev

    :(

  • JMenu with AWT component

    dear friends;
    i have added menu bar in Jframe which is containes menues.
    AWT component is added the the same frame .
    problem is:
    menues are overlapping with awt component while i clicked the menu bar.
    dear friends help me immediately.
    thank u

    dear friends help me immediately.It's your own fault or combining Swing and AWT widgets. You're not supposed to do that, as it can lead to strange effects. Like this one.

  • SetAccelerator in Java 6 wont work with invisible JMenuItem

    HI all,
    i have a problem with Java 6.
    I used an invisibleMenuItem to enable some shortkey. it works fine with Java 5.
    while with Java 6, the following methods wont work anymore.
    invisibleMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,inputEvent.CTRL_MASK));do u have any idea?

    sorry, i still dont figure it out. That was an overlooking.
    i tried to run the binding example with some little modification.
    http://java.sun.com/docs/books/tutorial/uiswing/components/examples/SliderDemo3.java
    original code
      textField.getInputMap().put(KeyStroke.getKeyStroke(
                                            KeyEvent.VK_ENTER, 0),
                                            "check");modified code
    textField.getInputMap().put(KeyStroke.getKeyStroke(
                      KeyEvent.CTRL_MASK, KeyEvent.VK_M),
                                            "check");then it wont listen to ctrl-M event. can anyone help?

  • JMenu - dynamicaly adding JMenuItem

    I'm making a JDesktopFrame that could contains inside itself JInternalFrame. Now, I would like to add in a JMenu the list of The JInternalFrame when its is opened and remove when is closed.
    can anybody help me?

    To add the menu item:myMenu.add( myMenuItem );To remove the menu item later:myMenu.remove( myMenuItem);Seems pretty obvious to me, what exactly were you confused about?

  • JMenu doesn't dissapear when menu is losing focus

    Hello everyone!
    I have a JMenu with several JMenuItems. The problem is that the JMenu doesn't dissapear when the menu is losing it's focus, for example when I click somewhere in the application window. I use the Windows look and feel for my application.
    Any ideas ? Thanks.

    Add some try/catch block. My guess is that you bump in some NullPointerException.

  • Several windows and grid questions

    Hello, I have a couple of Swing related questions that follow:
    Q 1)
    Imagine I'm writing a basic GUI that has 2 "windows": the main window and the about box window. Basicly there's a JMenu with a JMenuItem that has an action that will set the about box visibility to true.
    My question is: what's the most correct way to do this?
    a) declare both windows in the Gui constructor, having the main window's visibility set to true and the about box window visibility set to false, changing that visibility inside a actinPerformed () method
    b) declare the main window in the Gui constructor, and then creating the about box window inside the actionPerformed method, when the MenuItem is selected
    c) other. please explain
    Q 2)
    Is there any way to automaticly draw a grid within a JFrame or does it have to be done with Graphics' drawRect, drawLine and so on?
    Thanks in advance.

    Q1: c, have a getter for the aboutBox and instanciate when needed (also possible with b). If the user never clicks the menuItem, why instanciate and clean up later?
    Q2: DrawRect /line

Maybe you are looking for

  • Multiple PO's for a single PR reg

    Hi, The system incorrectly allows multiple PO's for a single PR.Then,I configured message no 00 06 076 & 400 as a error message and system is not allowing mutiple PO's for single PR and if PO Qty is greater than PR it's not allowing and it's ok. Now

  • Load image into holderMC

    Hi, I'm working on an application which places instances from my library onto the stage. Every instance has a movieclip inside it which is called holderMC. What I want to do is to load external images into holderMC except I can't seem to get it worki

  • DTW - UDT of Document Type

    Hi, Is it possible to implement DTW to UDT of Document Typeu2026 it displaying my UDT in Business object [drop down selection] selection... But while mapping fields itu2019s displaying code and name in target fields. I didnu2019t map this field with

  • Cannot disable sync in Firefox 8

    I am trying to find a way to break sync as painlessly as possible. I cannot allow my users to have sync for security reasons. So far I have attempted to edit the userChrome.css (scripts at the bottom) in the default profile to hide the tools menu ele

  • [Solved] can't enter package management in latest version of Emacs

    When I try to do something like 'package-install' or 'list-packages' in the latest version of Emacs, it refuses, complaining: Lisp error: (void-function package-desc-vers) package-desc-vers([(0 0 1) nil "Matrix themed Zone mode" tar]) ad-Advice-packa