JMenuItem.setIcon problem

When I create a JMenuItem and add an icon, the menu item text is greyed out (it's not disabled). When I remove the setIcon, the text appears normally. This is L&F independent.
I've tried various things to force the foreground color to black, but nothing works.
I'm using JRE 1.4.2_04.
Any suggestions?
Thanks
Ross

Now that I think about it, I remember that there are quite a few problems with setting button background colors due to conflicts with Windows desktop styles and the native button code. I assume that's involved here since JMenuItems are buttons.
However, in this particular case, I'm not trying to set any colors, just setting an icon. Why wouldn't that work?

Similar Messages

  • JMenuItem painting Problem

    Hi,
    I have painting problem with adding the JMenuItems dynamically. In the screen1 figure shown below, Menu 2 has has total 10 items, but initially we will show only three items. When the user clicks on the menu item ">>" all the Ten Items in Menu 2 are shown. But, All the 10 items are inserted in a compressed manner as shown in screen 2. When i click on the Menu 2 again, is shows properly as shown in screen 3.
    screen 1:
    <img src="http://img.photobucket.com/albums/v652/petz/Technical/screen1.jpg" border="0" alt="Screen 1"/>
    screen 2:
    <img src="http://img.photobucket.com/albums/v652/petz/Technical/screen2.jpg" border="0" alt="Screen 2"/>
    screen 3:
    <img src="http://img.photobucket.com/albums/v652/petz/Technical/screen3.jpg" border="0" alt="Screen 3"/>
    Here is the code:
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class MenuUI implements MouseListener
        JFrame frame;
        JMenuBar menubar;
        JMenu menu1,menu2;
        JMenuItem menuItem;
        JMenuItem lastMenuItem;
        String MENU1_ITEMS[] = {"ONE","TWO","THREE","FOUR","FIVE"};
        String MENU2_ITEMS[] = {"ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","TEN"};
        int MIN_MENU = 3;
        public MenuUI()
            menubar = new JMenuBar();
            /*menu1 = new JMenu("Menu 1");
            menu1.setMnemonic(KeyEvent.VK_1);
            menu1.getPopupMenu().setLayout(new GridLayout(5,1));
            menu2 = new JMenu("Menu 2");
            menu2.setMnemonic(KeyEvent.VK_2);
            menu2.getPopupMenu().setLayout(new GridLayout(5,2));*/
            menu1 = new JMenu("Menu 1");
            menu1.setMnemonic(KeyEvent.VK_1);
            menu2 = new JMenu("Menu 2");
            menu2.setMnemonic(KeyEvent.VK_2);
            menubar.add(menu1);
            menubar.add(menu2);
            createMinMenuItems();
            frame = new JFrame("MenuDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setJMenuBar(menubar);
            frame.setSize(500, 300);
            frame.setVisible(true);
        public void createMinMenuItems()
            for (int i = 0; i < MIN_MENU; i++)
                menuItem = new JMenuItem(MENU1_ITEMS);
    menu1.add(menuItem);
    lastMenuItem = new JMenuItem(">>");
    lastMenuItem.addMouseListener(this);
    menu1.add(lastMenuItem);
    for (int i = 0; i < MIN_MENU; i++)
    menuItem = new JMenuItem(MENU2_ITEMS[i]);
    menu2.add(menuItem);
    lastMenuItem = new JMenuItem(">>");
    lastMenuItem.addMouseListener(this);
    menu2.add(lastMenuItem);
    private void showAllMenuItems(int menuNo)
    if(menuNo == 1)
    menu1.remove(MIN_MENU);
    for (int i = MIN_MENU; i < MENU1_ITEMS.length; i++)
    menuItem = new JMenuItem(MENU1_ITEMS[i]);
    menu1.add(menuItem);
    menu1.updateUI();
    else if(menuNo == 2)
    menu2.removeAll();
    menu2.getPopupMenu().setLayout(new GridLayout((MENU2_ITEMS.length),1));
    for (int i = 0; i < MENU2_ITEMS.length; i++)
    menuItem = new JMenuItem(MENU2_ITEMS[i]);
    //menuItem.setMinimumSize(new Dimension(35,20));
    menu2.add(menuItem);
    menu2.updateUI();
    //menu2.getPopupMenu().invalidate();
    //menu2.getPopupMenu().repaint();
    //menubar.repaint();
    //menubar.invalidate();
    //menubar.getParent().repaint();
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
    public void mousePressed(MouseEvent arg0)
    System.out.println("mousePressed: Menu 1 selected: "+menu1.isSelected());
    System.out.println("mousePressed: Menu 2 selected: "+menu2.isSelected());
    if(menu1.isSelected())
    System.out.println("mousePressed: Menu 1: Show All Items");
    showAllMenuItems(1);
    else if(menu2.isSelected())
    System.out.println("mousePressed: Menu 2: Show All Items");
    showAllMenuItems(2);
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
    public void mouseClicked(MouseEvent evt)
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
    public void mouseEntered(MouseEvent arg0)
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
    public void mouseExited(MouseEvent arg0)
    /* (non-Javadoc)
    * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
    public void mouseReleased(MouseEvent arg0)
    public static void main(String[] args)
    MenuUI ui = new MenuUI();

    // menu2.updateUI();
    menu2.getPopupMenu().setVisible(false);
    menu2.getPopupMenu().setVisible(true);

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

  • I want to set an Action on a JMenu (not JMenuItem) but...

    ...it doesn't seem to work. I can set actions on JMenuItems no problem. But actions and actionlistening doesn't seem to work on JMenus. I can add MouseListener to a JMenu, but I REALLY want an action.
    can anyone help?
    Olly

    JMenu.addActionListener(yourListener) ?

  • JMenu inner: how I can?

    Hello!
    I have a little trouble with inner JMenu.
    I must to do a JMenu that contains a few of JMenu that haves a lot of JMenuItem; all components are created at run-time.
    For example, the first JMenu (called "FIRST") contains the JMenu 1,2,3,4..
    All 1,2,3 use their name as paramether for have a ResultSet that is used for building JMenuItem associated to JMenu 1,2,3...
    in picture
    FIRST------->1--->JMenuItem 0
    |
    |--->2--->JMenuItem 1
    | |
    | -->JMenuItem 1
    |
    --->3--->etc...
    There's the code:
    /*connection to db*/
    JMenu first=new JMenu();
    JMenu second=new JMenu();
    ResultSet rs_class=st.executeQuery(...);
    /*i have the voices for the first jmenu*/
    while(rs_class.next()){
    name_class=rs.class.getString(1);
    }/*end while for class*/
    /*i create the JMenu first using the arraylist classi for remember the element's name*/
    for(int i=0;i<classi.size();i++){
    name_class=classi.get(i);
    first=new JMenu(name_class);
    ResultSet rs_metodo=st.executeQuery(...);
    while(rs_metodo.next()){
    name_method=rs_metodo.getString(1);
    metodo.add(name_metodo);
    }/*end while JMenu second*/
    for(int j=0;j<metodo.size();j++){
    nome_metodo=metodo.get(j);
    second=new JMenu(name_method);
    ResultSet rs_param=st.executeQuery(...);
    /*i create the jmenuitem for jmenu second*/
    while(rs_param.next()){
    String p1=rs_param.getString(1);
    JMenuItem mi= new JMenuItem(p1);
    second.add(mi);
    }/*end while param*/
    first.add(second);
    }/*end method*/
    this.add(first);
    }/*end for of class*/
    }/*end method for JMenu-Jmenu-JMenuItem*/My problem is that second is not reset on the change of step but in all step him add the new JMenuItem() and him memorize all old JMenuItem.
    I want that, in all step, second take only JMenuItem generated in the step and only in this step.
    How must I code for have the reset of second JMenu?
    Thanks for every feed-back

    When a 430EX II is used wirelessly via E-TTL, it can only work in the "slave" mode (it can be an off-camera remote flash, but if it is used on-camera, it cannot work as a "master" to control the "slaves".)  Alsok the 430EX II has no radio, so it can only work in "optical" mode.
    The 600EX-RT is the flagship flash... it can be "master" or a "slave".  It can also work via "radio" or "optical".  
    So while the 600EX II is versatile, the 430EX II is more restrictive.  That means you have to use 430 off-camera and the 600 on-camera as the master.
    The ST-E3-RT is _only_ a radio trigger... it cannot trigger a flash optically.   The ST-E2 can trigger optically (but not radio).  
    The 5D III has no built-in trigger.  That means if you want to control both the 430 and 600 off-camera, you'd need an ST-E2 to do it.  
    When I bought my 5D III, I had a 430EX II and a 580EX II.  I've since bought a pair of 600EX-RT units and then finally added the ST-E3-RT controller.  I no longer use my 430EX II or 580EX II (those are "on loan" to friends.  I say "on loan" because I realize I don't need them anymore and so there's really no reason for them to ever return them.  At this point, I might as well just call them "gifts".)
    Tim Campbell
    5D II, 5D III, 60Da

  • GlassPane and JMenuBar -- PLEASE HELP

    I am implementing my own glasspane. I am having trouble with JMenuBar. I read javadocs and notes and I still can't get it to work. First thing that I do is that for each mouseevent i call redispatchMouseEvent();
    public void mouseMoved(MouseEvent me) {     redispatchMouseEvent(me);  }
    public void mouseDragged(MouseEvent me) {redispatchMouseEvent(me); }
    public void mouseClicked(MouseEvent me) {redispatchMouseEvent(me);}
    public void mouseEntered(MouseEvent me){redispatchMouseEvent(me);}
    public void mouseExited(MouseEvent me){redispatchMouseEvent(me); }
    public void mousePressed(MouseEvent me){redispatchMouseEvent(me);}
    public void mouseReleased(MouseEvent me){redispatchMouseEvent(me);    }Inside redispatchMouseEvent() I check to see if mouse is on jMenuBar, if so I get instance of JMenu selected and save it;
         if (containerPoint.y < 0)
             if (containerPoint.y + menuBar.getHeight() >= 0)
    // MOUSE IS ON JMENUBAR AREA
              containerPoint = SwingUtilities.convertPoint(this, glassPanePoint, menuBar);
              component = SwingUtilities.getDeepestComponentAt(menuBar, containerPoint.x, containerPoint.y);
              Point componentPoint = SwingUtilities.convertPoint(this, glassPanePoint, component);
              if (component != null)
                  component.dispatchEvent(new MouseEvent(component, me.getID(), me.getWhen(), me.getModifiers(), componentPoint.x, componentPoint.y, me.getClickCount(), me.isPopupTrigger()));
    // SAVE HANDLE TO JMENU
                  if (component instanceof JMenu)
                   menu = (JMenu)component;
           }I check to see if (menu != null ) if not then I'm inside a menu. so I call processMouseEvent to handle movement and selection of a JMenuItem, the problem that I am getting is that as the mouse moves the JMenuItems are highlighted properly but when I click on it nothing happens. what am I doing wrong?
    else
             if (menu != null)
              System.out.println("menu event");
              Point componentPoint = SwingUtilities.convertPoint(this, glassPanePoint, menu);
              MenuSelectionManager.defaultManager().processMouseEvent((new MouseEvent(menu, me.getID(), me.getWhen(), me.getModifiers(), componentPoint.x, componentPoint.y, me.getClickCount(), me.isPopupTrigger())));
             }elsePLEASE HELP!!!
    Here is complete source excerpt;
        // mouse listeners
        public void mouseMoved(MouseEvent me)
         redispatchMouseEvent(me);
        public void mouseDragged(MouseEvent me)
         redispatchMouseEvent(me);
        public void mouseClicked(MouseEvent me)
         System.out.println("click");
         menu = null;
         redispatchMouseEvent(me);
        public void mouseEntered(MouseEvent me)
         redispatchMouseEvent(me);
        public void mouseExited(MouseEvent me)
         redispatchMouseEvent(me);
        public void mousePressed(MouseEvent me)
         System.out.println("press");
         redispatchMouseEvent(me);
        public void mouseReleased(MouseEvent me)
         System.out.println("release");
         redispatchMouseEvent(me);
        JMenu menu;
        private void redispatchMouseEvent(MouseEvent me)
         Point glassPanePoint = me.getPoint();
         Container container = contentPane;
         Point containerPoint = SwingUtilities.convertPoint(this, glassPanePoint, contentPane);
         Component component = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y);
         if (containerPoint.y < 0)
             if (containerPoint.y + menuBar.getHeight() >= 0)
              System.out.println("MenuBar:component="+component);
              containerPoint = SwingUtilities.convertPoint(this, glassPanePoint, menuBar);
              component = SwingUtilities.getDeepestComponentAt(menuBar, containerPoint.x, containerPoint.y);
              Point componentPoint = SwingUtilities.convertPoint(this, glassPanePoint, component);
              if (component != null)
                  component.dispatchEvent(new MouseEvent(component, me.getID(), me.getWhen(), me.getModifiers(), componentPoint.x, componentPoint.y, me.getClickCount(), me.isPopupTrigger()));
                  if (component instanceof JMenu)
                   menu = (JMenu)component;
             else
              System.out.println("Decor");
         else
             if (menu != null)
              System.out.println("menu event");
              Point componentPoint = SwingUtilities.convertPoint(this, glassPanePoint, menu);
              MenuSelectionManager.defaultManager().processMouseEvent((new MouseEvent(menu, me.getID(), me.getWhen(), me.getModifiers(), componentPoint.x, componentPoint.y, me.getClickCount(), me.isPopupTrigger())));
             }else
              if (component != null)
                  System.out.println("component");
                  Point componentPoint = SwingUtilities.convertPoint(this, glassPanePoint, component);
                  component.dispatchEvent(new MouseEvent(component, me.getID(), me.getWhen(), me.getModifiers(), componentPoint.x, componentPoint.y, me.getClickCount(), me.isPopupTrigger()));
         repaint();
    }

    You need to set popup menus to be non-lightweight in your GUI code, before you add your JMenu objects to the JMenuBar:
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);I'm not entirely sure why this is necessary here, so if someone would care to explain, I'm all ears ;)
    Your code is overly complicated too. You don't need to test for instanceof JMenu or anything like that. Your redispatch method should look something like this (adapted from the Sun tutorial):
    private void redispatchMouseEvent(MouseEvent event) {
              Point glassPanePoint = event.getPoint();
              Container container = contentPane;
              // Get mouse event point in content pane's coordinate system
              Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, contentPane);
              // If we're not in the content pane
              if (containerPoint.y < 0) {
                   // Then we're either in the menu bar..
                   if (containerPoint.y + menuBar.getHeight() >= 0) {
                        // Get mouse event point in menu bar's coordinate
                        // system
                        Point menuBarPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, menuBar);
                        // Get deepest visible component lying under the mouse event
                        Component component = SwingUtilities.getDeepestComponentAt(menuBar, menuBarPoint.x, menuBarPoint.y);
                        // Do nothing if no component is found
                        if (component != null) {
                             // Get mouse event point in deepest component's coordinate
                             // system
                             Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
                             // Redispatch mouse event to the deepest component
                             component.dispatchEvent(new MouseEvent(component, event.getID(), event.getWhen(), event.getModifiers(), componentPoint.x,
                                       componentPoint.y, event.getClickCount(), event.isPopupTrigger()));
                        // ..or else we're over a non-system window decoration
                   } else {
              } else {
                   // Get deepest visible component lying under the mouse event
                   Component component = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y);
                   // Do nothing if no component is found
                   if (component != null) {
                        // Get mouse event point in deepest component's coordinate
                        // system
                        Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component);
                        // Redispatch mouse event to the deepest component
                        component.dispatchEvent(new MouseEvent(component, event.getID(), event.getWhen(), event.getModifiers(), componentPoint.x,
                                  componentPoint.y, event.getClickCount(), event.isPopupTrigger()));
         }HTH.

  • JMenuItem Problems ?

    hi,i got problems,i cannot view the JMenuItem ?what's wrong ?
    satu.java
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    public class satu {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              JFrame.setDefaultLookAndFeelDecorated(true);
              final JFrame appp = new JFrame("TEST ");
              appp.setSize(150,180);
              appp.setUndecorated(true);
              appp.setResizable(false);
              testmenu m = new testmenu();
              appp.setJMenuBar(m.createbar());
              appp.setContentPane(m.createContentPane());
              m.start();
              appp.setSize(540,430);
              //dua m = new dua(appp);
            //m.init();
              //TestHeaderRenderer m = new TestHeaderRenderer();
              appp.add(m,BorderLayout.CENTER);   
             appp.setVisible(true);
             //appp.setLocationRelativeTo(null);
              appp.addWindowListener(new WindowAdapter() {
                           public void windowClosing(WindowEvent evt) {
                          appp.setVisible(false);
                          appp.dispose();
    }testmenu.java
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Panel;
    import java.awt.event.KeyEvent;
    import java.applet.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class testmenu extends Applet {
         String sessionid,usersession;
         JMenuItem menuout;
        Panel contentPane;
        public JMenuBar createbar(){
              JMenuBar menu1 = new JMenuBar();
              JMenu menustart = new JMenu("File");
              menustart.setMnemonic(KeyEvent.VK_F);
            JMenu menutool = new JMenu("Tools");
            menutool.setMnemonic(KeyEvent.VK_T);
              menuout = new JMenuItem("New");
              menustart.add(menuout);
              menu1.add(menustart);
              menu1.add(menutool);
              return menu1;
         public Container createContentPane() {
              contentPane = new Panel();
              contentPane.setBackground(Color.BLACK);
            gbrutama x = new gbrutama();
            contentPane.add(x);
            return contentPane;
    class gbrutama extends Applet{
       public gbrutama() {
       public void paintComponent(Graphics g){
        g.drawLine(0,0,200,200);
    }when i click on menu "File",why i cannot view "New" JMenuItem ?Please someone help me,please...
    thanks.

    for your old code it worked :Check it
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Panel;
    import java.awt.event.KeyEvent;
    import java.applet.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    public class satu {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              JFrame.setDefaultLookAndFeelDecorated(true);
              final JFrame appp = new JFrame("TEST ");
              appp.setSize(150,180);
              appp.setUndecorated(true);
              appp.setResizable(false);
              testmenu m = new testmenu();
              appp.setJMenuBar(m.createbar());
              appp.setContentPane(m.createContentPane());
              m.start();
              appp.setSize(540,430);
              //dua m = new dua(appp);
            //m.init();
              //TestHeaderRenderer m = new TestHeaderRenderer();
              appp.add(m,BorderLayout.CENTER);
             appp.setVisible(true);
             //appp.setLocationRelativeTo(null);
              appp.addWindowListener(new WindowAdapter() {
                           public void windowClosing(WindowEvent evt) {
                          appp.setVisible(false);
                          appp.dispose();
    //testmenu.java
    class testmenu extends Applet {
         String sessionid,usersession;
         JMenuItem menuout;
        javax.swing.JPanel contentPane;
        public JMenuBar createbar(){
              JMenuBar menu1 = new JMenuBar();
              JMenu menustart = new JMenu("File");
              menustart.setMnemonic(KeyEvent.VK_F);
            JMenu menutool = new JMenu("Tools");
            menutool.setMnemonic(KeyEvent.VK_T);
              menuout = new JMenuItem("New");
              menustart.add(menuout);
              menu1.add(menustart);
              menu1.add(menutool);
              return menu1;
         public Container createContentPane() {
              contentPane = new javax.swing.JPanel();
              contentPane.setOpaque(true);
              contentPane.setBackground(Color.BLACK);
            gbrutama x = new gbrutama();
            contentPane.add(x);
            return contentPane;
    class gbrutama extends Applet{
       public gbrutama() {
       public void paintComponent(Graphics g){
        g.drawLine(0,0,200,200);
    }wait let me see your new modified code...

  • JMenuItem ActionEvent Dinamically - Problems

    Hi, friends
    I am trying to use a JMenu and a JMenuItem wich are dinamicaly
    constructed getting data using a Oracle's Database Table.
    They are working fine, but I can't figured out how can I add
    ActionEvent dinamicaly. The piece of my code is down here:
    JMenuBar menuOpcao = new JMenuBar;
    JMenu menu[] = new JMenu[5];
    JMenuItem submenu[] = new JMenuItem[20];
    for (x=0;x<menu.lenght;x++)
    menu[x] = new JMenu();
    menu[x].setLabel(" menu " + x); //menu 1, menu 2...
    for (y=0;y<submenu.lenght;y++)
    submenu[y] = new JMenuItem();
    submenu[y].setLabel(" submenu " + y); // submenu 1...
    submenu[y].addActionListener(new ActionListener()
    { public void actionPerformed(ActionEvent e){
    System.out.println(e);}
    menu[x].add(submenu[y];
    menuOpcao.add(menu[x]);
    My problem: the ActionEvent is not working, because I need know
    wich Item I am clicking, so I can execute a query in a Database.
    Any Ideas?
    Thank you.
    null

    You don't use MouseListeners. You use ActionListeners.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus for working examples.

  • Problems adding JMenuItem-s

    Hello!
    I have encountered a problem and I don't know where my JMenuItem-s disappear. The output for the next program:
    public class test {
    public test() {
    public static void main(String[] args) {
    JPanel panel = new JPanel();
    JMenu menu = new JMenu("Meniu");
    JMenuItem item1 = new JMenuItem("1");
    JMenuItem item2 = new JMenuItem("2");
    menu.add(item1);
    menu.add(item2);
    System.out.println("The menu has "+menu.getItemCount()+" item(s).");
    JMenuItem item3 = menu.getItem(0);
    System.out.println("The menu has "+menu.getItemCount()+" item(s).");
    panel.add(item3);
    System.out.println("The menu has "+menu.getItemCount()+" item(s).");
    is:
    The menu has 2 item(s).
    The menu has 2 item(s).
    The menu has 1 item(s).
    Shouldn't it be 2-2-2? One of my items is gone. Can you tell me what can I do? Thanks.

    The problem is (I think, somebody correct me if I'm mistaken), you're taking the first item in your menu and adding it to the panel. A Component can only be a child of one thing at a time, so adding that first item to the panel removes it from the menu.

  • Problem with JMenuItem, method isArmed()

    Hi everybody,
    I want hide my menu when I "open" it and click in another part of the application.
    it did not work when I made the verification using the method isArmed() in JMenuItem.
    I added a mouseListener in my JPanel, that is located below my JMenuBar. In mouseClicked(), i do the verification like this:
    public void mouseClicked(MouseEvent mouseevent) {
              int contador = ViewFacade.getViewFacade().getMenuBar().getMenuCount();
              for (int i = 0; i < contador; i++){
                   JMenu myMenu = (JMenu)ViewFacade.getViewFacade().getMenuBar().getMenu(i);
                   for (Component itensMenu : myMenu.getMenuComponents()){
                        if (itensMenu instanceof JMenu){
                             if (((JMenu)itensMenu).isArmed()){
                                  ((JMenu)itensMenu).setArmed(false);
                        }else if (itensMenu instanceof JMenuItem){
                             if (((JMenuItem)itensMenu).isArmed()){
                                  ((JMenuItem)itensMenu).setArmed(false);
    But it did not work. Even when my JMenu is "armed", it doesn't work.
    Can anybody give me a hint??
    thanks, Guilherme

    Don't understand what you are doing playing with the isArmed() method. A JMenu will automatically disappear when you click on another part of your application, so no custom code is required.
    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.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.

  • Problems with event handling in JmenuItem

    Hello:
    I'm trying to handle an event for a menuItem and tool bar item: with this code:
    newBallotAction = new AbstractAction("newBallot")
    public void actionPerformed(ActionEvent e)
    try{
    System.out.println("MainWindow newBallotAction");
    Ballot ballot = new Ballot();
    System.out.println("MainWindow newBallotAction 2nd");
    DDNewBallotWindow ddNewBallotWindow = new DDNewBallotWindow(ballot);
    if (ballot != null) // <ballotName>, <ballotOptionsNumber> , <ballotOption1>, <ballotOption2>, .., <ballotOption(optionsNumber)>
    brothers.msgToBrothers("<Ballot>" + "<origin>" + myName + "</origin>"+ ballot.toRep() +"</Ballot>" , myName);
    else
    System.out.println("MainWindow ballot null");
    }catch(Exception f){
    System.out.println("MainWindow newBallotAction exception" + e);
    JMenuItem ballotMIDdMenu = new JMenuItem("New Ballot");
    ballotMIDdMenu = fileMenu.add(newBallotAction);
    ddMenu.add(ballotMIDdMenu);
    It produces the next exception:
    MainWindow newBallotAction exceptionjava.awt.event.ActionEvent[ACTION_PERFORMED,cmd=newBallot] on javax.swing.JMenu$2[,1,49,137x21,alignmentX=null,alignmentY=null,border=javax.swing.plaf.metal.MetalBorders$MenuItemBorder@55a338,flags=264,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,right=2],paintBorder=true,paintFocus=false,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=newBallot]
    It's really complex ... I'm desperado ;)
    Thanks in advance, Nacho.

    Hi,
    The exception is propably occuring in the Ballot() constructor (which you didn't post).
    And, as dukeman already mentionned, you are printing out the ActionEvent object and not the Exception itself.

  • JMenuItem and MouseListener Problems

    I add the MouseListener to the JMenu, the event works.
    but when I add the MouseListener to the JMenuItem, it didn't work?
    why?
    the following is my code:                         jMenuItemRelogin = new JMenuItem();
                             jMenuLogin.add(jMenuItemRelogin);
                             jMenuItemRelogin.setText("Relogin");
                             jMenuItemRelogin.addMouseListener(new MouseAdapter(){
                                  public void mouseClicked(MouseEvent evt){
                                       reloginMouseClicked(evt);
                             });

    You don't use MouseListeners. You use ActionListeners.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus for working examples.

  • InternalFrameListener and JMenuItem problem

    Hi there, I did the following (just an outline, I know, that program is not working.... :))
    class A{
    static JMenuItem m_saveMenu;
    A(){
    JMenuBar mB = new JMenuBar();
    m_saveMenu = new JMenuItem("Save As...");
    class B{
    JInternalFrame iFrame = new JInternalFrame();
    iFrame.addInternalFrameListener(new MyListener());
    class MyListener extends InternalFrameAdapter{
         public void internalFrameActivated (InternalFrameEvent e){
              A.m_saveMenu.setEnabled(true);     }
         public void internalFrameDeactivated(InternalFrameEvent e){
    A.m_saveMenu.setEnabled(false);
    So if I (in my working program) create a new JInternalFrame and activate it I get the following error message:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    why could that be??
    Thx
    Charly

    hi,
    I mean this is obvious: You didn't initialize the menu item, you just declared it! And the listener might be used before the constructor of class A is called.
    You could do the following now:
    static JMenuItem m_saveMenu=new JMenuItem("Save As...");
    unless you are sure that the constructor of class A and with it the initialization of the menu item goes ahead.
    best regards, Michael

  • Problems with JMenuItem

    I want my menuitem to show the text "New(N) Ctrl+N",and when i press the combination key ctrl and N the system will create an Event,which has the same effect with I click the menuitem.
    My code is:
               javax.swing.KeyStroke stroke;
               int event=java.awt.event.KeyEvent.VK_N;
               int inputEvent=java.awt.event.InputEvent.CTRL_DOWN_MASK;
               stroke=javax.swing.KeyStroke.getKeyStroke(event, inputEvent);
               jMenuItemNew.setAccelerator(stroke);
               but when i press the combination key Ctrl and N,there is no response.
    Did i do wrong?
    Any suggestions would be welcom!
    thanks in advance!

    I want my menuitem to show as"New(N) " and there is an underline under the second letter N.my code is:
    jMenuItemNew.setMnemonic(java.awt.event.KeyEvent.VK_N);when i press the combination key Alt and N,it has the same effect wih I click the menuitem.But how can i let it show as "New(N) " with a line under the second letter N.
    thanks!

  • Disabled JMenuItem doesn show animated gif

    Hi there
    I would like to have a popup menu with actions that are enabled after they have finished with some background task taking some time. Basically this works fine for the enabling action on a shown popup. However, adding an animated gif as the icon or disabled icon does not show it in disabled state. In enabled state it works perfect. Please have a try with the sample code. You should see the disabled item for 2 secs and the icon is not showing up. After being enabled, it does. Invoking the menu again shows the animated gif in its last state left, but not moving any more.
    I guess, repaints are not done appropriately in disabled state... Any ideas how to solve that would be highly appreciated :-)
    Actually I used the icon at http://mentalized.net/activity-indicators/indicators/pascal_germroth/indicator.white.gif
    Cheers
    Daniel
    public class Main
      public static void main(String[] args)
        final JFrame frame = new JFrame();
        frame.addMouseListener(new MouseAdapter()
          public void mousePressed(final MouseEvent e)
            final JPopupMenu popup = new JPopupMenu();
            popup.add(new JMenuItem("Open..."));
            popup.add(new JMenuItem("Close"));
            final JMenuItem action = new JMenuItem("Long loading until enabled");
            action.setIcon(new ImageIcon("C:/spinner.gif"));
            action.setDisabledIcon(new ImageIcon("C:/spinner.gif"));
            popup.add(action).setEnabled(false);
            popup.show(e.getComponent(), e.getX(), e.getY());
            SwingUtilities.invokeLater(new Runnable()
              public void run()
                try
                  Thread.sleep(2000);
                  action.setEnabled(true);
                catch (InterruptedException e1)
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }Edited by: daniel.frey on Apr 22, 2009 7:50 AM

    The problem is that you are causing the EDT to sleep, which means the GUI can't repaint itself. Read the section from the Swing tutorial on Concurrency to understand what is happening.

Maybe you are looking for