JMenu and JMenuItems

hi
does anybody know how i can disable menuitems
and enable them on some given events?
would help me very much!
thanx

A good way to do this is to use Actions - define an Action object for each menu item (including text and an icon if you want), then just add the actions to the menu, and it will show them with icons automatically.
Then if you do setEnabled(false) on the action, the menu item is greyed out. Also, you can add these Actions to other components such as a JToolBar, which would automatically render them as buttons (these also get greyed out when disabed).
The big benefit is that all your "action" code is in one place, so the menu and the toolbar both call the same code.
For a tutorial, see
http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html

Similar Messages

  • JMenu and JMenuItem - Images

    How to put an image in front of the JMenu text?
    JMenuItem has a constructor to insert the icon.
    Is their a reason why it not in the JMenu constructors?
    Sometimes I just want to put a 16 pixel gap in front of the JMenuItem or JMenu if it has no Image. Can one do that without inserting a blank
    Image?
    Thanks

    Have you tried just setting it via setIcon()? Since both JMenu and
    JMenuItem inherit from AbstractButton, this may work; I say may
    since more than likely it is up to the L&F UI to do the right thing.
    A quick browse shows that it ought to work for at least the basic
    L&Fs though.
    As far as the empty gap, looks like you might be out of luck by
    default, but this too is up to the L&F. For instance, some look and
    feels line up the text properly if an item doesn't have an icon.
    As a quick fix, though, you could probably just set the icon to
    something like
    menuItem.setIcon( new Icon() {
        public int getIconWidth() { return 16; }
        public int getIconHeight() { return 0; }
        public void paintIcon(Component c, Graphics g, int x, int y) {}
    });: jay

  • JMenu and JMenuItem

    Is it possible to have a JMenuItem within a JMenuItem? For example: Menu would drop down to a JMenuItem with two choices and when you click on one of the two choices another JMenuItem would have more choices available?

    Read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus for an example.

  • Custom text for JMenu and JMenuItem

    hey guys
    right now i can do a :
    JMenu menu = new JMenu("File");but how can i customize the text on the Menu a.k.a "file" so may be it looks bigger or a different color ?
    ive looked at the API i can see that JMenu takes "Action" object too which describes the look. I know Action is an interface and i havent been able to find a suitable class that implements this interface
    so how should i go about changing the text look/feel ?
    thank in advance

    so may be it looks bigger or a different color ?Read the API. There are many different set??? methods which allow you to change the properties of the component including the font size and color of the text.
    i can see that JMenu takes "Action" object too which describes the look.The Action has nothing to do with the look (other then providing the text to display). It has to do with the Action that happens when you select the menu item.

  • Using JMenu and JMenuItem

    I have a JMenu attached to a JFrame, along with a panel and a graphic object which extends Canvas. When I click the Menu bar, the menu does not show, it actually falls behind the Canvas. I can see it if I remove the Canvas. How do you make it appear over the Canvas or the items drawn over the Canvas?
    Any help will be greatly appreciated.
    Pradeep Gupta
    [email protected]
    Mon 03Nov03 10:31

    You are mixing heavyweight and lightweight components. Can you subclass JComponent or JPanel instead of Canvas? That would solve your problem.

  • 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 and making the popup always visible

    hi,
    i need to keep the menu's popup visible always and eventually the selection of an item even when the focus moves to another component-a text field nearby for example.can this (and how if it is) be achieved or it is totally up to the look and feel and i can't do much about it?
    thank you.

    just for the record,it seems it actually is doable.at least i have a prototype working.it involves removing default mouse listeners from jmenu i jmenuitem and installing "custom" ones that manage the transition of the menu from one state to another.

  • Accessing JMenu through JMenuItem

    How can I get access to the JMenu object having only JMenuItem contained in it?
    JMenu menu = new JMenu("Menu");
    JMenuItem menuItem = new JMenuItem("Menu Item");
    menu.add(menuItem);
    // Here I have only reference to 'menuItem'
    Thanks,
    TTauruSS

    looks like you can go down but not up.
    If you have a group of JMenu's then just go through each one, and use
        MenuElement []comps;
        if(menu.isMenuComponent(myMenuItem)) {
    // its in here...
    comps = menu[i].getSubElements();
    combination of the above should let you find what your looking for. Note that searching through a menu lends itself to some recursive coding.
    James.

  • JMenu.add(JMenuItem)

    Can I just say to start with. I pressed the browser back button from the preview page and it lost my whole post. How annoying is that?
    Anyway.
    Does anyone have any idea why the JMenu.add(JmenuItem) method might not work? It does not throw any exceptions, the menu item is simply not added. I basically have 5 lines of very similar code, the first 2 items are added fine, but the last 3 are not. I have stepped through the code and the last 3 menu itmes look fine, they just dont appear in the menu. I am totally stuck. Please help

    Hello,
    if you have code like this.JMenu menu=new JMenu("Menu");
    JMenuItem item=new JMenuItem("item");
    menu.add(item);
    menu.add(item);only the last item will be visible in the menu and the first will be removed.
    Swing is looking if the component you want to add to a container equals any item in the component hyrarchy .
    Regards,
    Tim

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

  • JMenu and Documentation

    Hello friends, couple questions here. Main one i am confused with is the Documentations. I cant quite seem to grasp how to use what they provide. If anyone would be so kind as to take the time and explain to me how to use what the documentation offers i would be grateful.
    http://wwwswt.fzi.de/~jjh/tools/swing/products/jfc/swingdoc-current/api/com.sun.java.swing.JMenuBar.html
    here is a link to a documentation of JMenu and how to make one but i do not get how to apply this into a program. Thank you very much - Jeff

    Specificially, you want this page
    http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    This is part of a much bigger tutorial, here
    http://java.sun.com/docs/books/tutorial/
    There are also more tutorials if you click on Tutorials in the upper left of this page.

  • JMenus and JMenuItems

    i have a JMenu called jMenu2, in its action performed method i would like it to add to the bottom of its list a new JMenuItem while the program is running.
    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
           jMenu2.add("hi");
    }so why can i not see this new menu item? i have tried many refreshing methods from JMenu with no luck

    I wouldn't expect it to show up immediately if it's being added as a result of clicking another item on the same JMenu, only next time you pull that JMenu down. If that doesn't happen, I would try creating a new JMenuItem("hi"), call setVisible(true) on it, and then add it to the JMenu. You shouldn't need to revalidate or repaint anything.

  • JMenu and JTabbedPane questions

    Hello I got 2 questions :
    1) Is it possible to change the icon of JMenu when the mouse cursor is on it ? setRolloverIcon function doesnt work in this case, like it does for the JButton.
    2) When I create my application I got 1 JTabbedPane object visible. Now, every time I click a selected JMenuItem, I wanna add another JTabbedPane object to the window. So in the class MyMenu I got this code in actionListener:
    if(arg.equals("menu1")) {
         JTabbedPane tabbedPane = new JTabbedPane();
         tabbedPane.addTab("tab", null, null, "nothing");
         frame.getContentPane().add(tabbedPane);
    The problem is that it doesnt appear on the window, but instead when I resize it, there is a vertical line in the place where the right "edge" of the old window was.
    Can anyone tell me what do I do wrong ?
    Thx in advance.

    Actually I dont know but the simpliest way seems to be subclassing the menu Item, and listen for mouse events. When you learn a better way to do it you can change your code :)
    Java always allowed me to do such tricks :)

  • JMenu and Paint Problem

    Hello,
    I have been teaching my self Java and I have become quite proficient with it, however, I have a problem that I can not fix, or get around.
    I have a JMenuBar in a JFrame with some JMenu�s containing JMenuItems. I also have a JPanel that I draw inside (I Know that is probably not the wisest way to draw things, but it was the way I first learned to draw and now my program is too big and it is not worth while to change). Any ways, I draw some graphics inside of this JPanel.
    The menu items change the drawings; this is done by repainting the JPanel Graphic. However, when I click one of the menu items, the JPanel paints but there is a residual of the JMenu in the background that will not disappear.
    The menu is closed and if I open and then close the menu the residual goes away.
    => I would like to know how to prevent the residual from appearing?
    The problem also occurs when I use the popup menus outside of the JmenuBar.
    What I think is wrong.
    I think my problem is with the repaint. I don�t think the JFrame is repainting. I think I am simply repainting all the components in the JFrame but not the JFrame itself and thus the residual is not cleared from the JFrame. I don�t know how to fix this but I believe that is the problem because when I minimize the JFrame then Maximize it the JFrame will not paint, and I can see right through the JFrame, but the components paint fine.
    Sorry for the long question, but I don�t know what would be helpful.
    Any advice would be appreciated,
    Thank you
    Seraj

    // This is the code that listens for the menu item
    private void RBmmActionPerformed(java.awt.event.ActionEvent evt) {                                    
            calc.setIN(false);
            updateData();                    // updates some data
            paint2();                           // my special draw fuction shown below
        public void paint2()                          // this the special paint that draws on the JPanel
            Graphics page = jPanel1.getGraphics();
            if(start_end)
                myPic.draw(page);
            else
                page.setColor(Color.WHITE);
                page.fillRect((int)(OFFSET.getX()), (int)(OFFSET.getY()), (int)(R_BOUND-OFFSET.getX()), (int)(L_BOUND-OFFSET.getY()));
            repaint();             
    public void paint(Graphics g)               // this is the regular paint methode
            MessageHandler();
            ATD_age.repaint();
            StanderdCal.repaint();
            ChildSRF.repaint();
            MessageArea.repaint();
        }I hope that is helpful

  • JMenu and JList

    I want to hava a menu that would have some of the same functionality as a JList, such as the cell renderer, the borders and the list models. I'm working inside a JApplet so creating JPopupMenus are out because of it seems to open new Windows in browsers and has that ugly Applet Window warning.
    I want to open pop up menus over the list elements.
    For example, I have a JList that holds user names for a chat room. When an element in that JList is clicked I want to open a menu that lists commands like "go to users homepage", "private chat", "kick out", etc.
    I've written an applet that uses JMenus. But I'd like to have the user list remain a JList because my applet uses the ListModel to pass the list's content to different parts of the program.
    I'd like to have similar functionality to the following (but with a JList instead of a JMenuBar holding the contents of the list)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MenuTestApplet extends JApplet{
    JPanel p = new JPanel(new BorderLayout());
    JMenuBar menuBar = new JMenuBar();
    JScrollPane scroll;
    public MenuTestApplet(){
         getContentPane().add(p, BorderLayout.CENTER);
         menuBar.setBackground(Color.blue.brighter().brighter());
         menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.Y_AXIS));
         for (int i=1; i<50;i++){
         addNewMenu("Menu "+i);
         p.add(new JLabel("nothing here"), BorderLayout.CENTER);
         scroll = new JScrollPane(menuBar);
         p.add(scroll, BorderLayout.CENTER);
    public void addNewMenu(String title){
         JMenu m = new JMenu(title);
         m.setBackground(Color.blue.brighter());
         JMenuItem item = new JMenuItem("one");
         item.setBackground(Color.blue.brighter());
         m.add(item);
         item = new JMenuItem("two");
         item.setBackground(Color.blue.brighter());
         m.add(item);
         item = new JMenuItem("THR33");
         item.setBackground(Color.blue.brighter());
         m.add(item);     
         m.setMinimumSize(m.getPreferredSize());
         m.setMenuLocation(7, 3);
         menuBar.add(m);
    I'm just looking for ideas right now.
    thanks

    would simply adding JMenu's to the JList do the trick?
    this was suggested by someone to me, but I thought that the elements in the JList are simply painted panels that use the objects toString() in the CellRenderer.

Maybe you are looking for