JMenuItem and MouseListener

Hi there!!
I'm working with nested menus.
Anyone knows if a JMenuItem doesn't catch mouseClicked() event when it belongs to a nested menu?
I can work with mousePressed() and mouseReleased() as a "mouse click", but i'd like to know the answer to it.
Regards, eyitikawa

S. pschugg, thanks for the reply.
I was using ActionListeners too.
But I need a effect of "on mouse over" a JMenuItem change its style and "on mouse out" the same returns to its original state. That's why I changed to MouseListener.
Does anyone ever needed this kind of effect?
Regards, eyitkawa.

Similar Messages

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

  • JMenuItem and JTextField doesn't look right after upgrading to Java 8

    I just upgraded to JDK 8u25
    I have a legacy Swing application, which makes use of JMenuItem and JTextField
    I realize, after upgrading, there is a bolder grey vertical border at the left side of JMenuItem and JTextField
    JMenuItem
    JTextField
    This only happen, if I were using look n feel com.sun.java.swing.plaf.windows.WindowsLookAndFeel
    Before that, I never have such problem. Anyone know is there any workaround for such problem?
    Here's the code example to demonstrate the problem.
    package javaapplication5;
    * @author yccheok
    public class NewJFrame extends javax.swing.JFrame {
         * Creates new form NewJFrame
        public NewJFrame() {
            initComponents();
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jTextField1 = new javax.swing.JTextField();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            jMenu2 = new javax.swing.JMenu();
            jMenuItem1 = new javax.swing.JMenuItem();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jMenu1.setText("File");
            jMenuBar1.add(jMenu1);
            jMenu2.setText("Edit");
            jMenuItem1.setText("jMenuItem1");
            jMenu2.add(jMenuItem1);
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(21, 21, 21)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(232, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(19, 19, 19)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(230, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
         * @param args the command line arguments
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Windows".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            //</editor-fold>
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration                  
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            //</editor-fold>
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JMenu jMenu1;
        private javax.swing.JMenu jMenu2;
        private javax.swing.JMenuBar jMenuBar1;
        private javax.swing.JMenuItem jMenuItem1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration                  

    The site looks OK -- actually quite impressive for what appears to be a from-scratch design.
    In Opera 10 under Snow Leopard 10.6.1, the design doesn't start to explode until the horizontally scrolling marquee comes across. I would strongly recommend just removing that marquee; it is an extremely outdated element of web design. If you do that, the design shouldn't blow up on you in other browsers.

  • KeyListener and MouseListener...How?

    I have a JTable and I want to add some KeyListener and MouseListener events to do following functions:
    - When PageDown is pressed, function NextPage(){...} is invoked
    - When a row is selected, then press Enter, function Select(){...} is invoked
    - Or when a row is clicked, function Select(){...} is invoked
    - When ESC is pressed function Exit(){...} is invoked
    Thanks all your help and sorry for my poor English :)

    I think you should look at using Actions. Here is a simple example that shows how to map Actions to KeyStrokes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class KeyboardAction extends JFrame
        public KeyboardAction()
            JPanel panel = new JPanel();
            setContentPane( panel );
            JTextField textField1 = new JTextField("Ctrl+1 or Ctrl+2", 10);
            panel.add( textField1 );
            JTextField textField2 = new JTextField("Ctrl+2", 10);
            panel.add( textField2 );
            //  Change the input map of the text field,
            //  therefore, Ctrl+1 only works for the first text field
            Action action1 = new SimpleAction("1");
            Object key1 = action1.getValue(Action.NAME);
            KeyStroke ks1 = KeyStroke.getKeyStroke(KeyEvent.VK_1, KeyEvent.CTRL_MASK);
            textField1.getInputMap().put(ks1, key1);
            textField1.getActionMap().put(key1, action1);
            //  Change the input map of the panel
            //  therefore, Ctrl+2 works for both text fields added to the panel
            Action action2 = new SimpleAction("2");
            Object key2 = action2.getValue(Action.NAME);
            KeyStroke ks2 = KeyStroke.getKeyStroke(KeyEvent.VK_2, KeyEvent.CTRL_MASK);
            panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks2, key2);
            panel.getActionMap().put(key2, action2);
        class SimpleAction extends AbstractAction
            public SimpleAction(String name)
                putValue( Action.NAME, "Action " + name );
            public void actionPerformed(ActionEvent e)
                System.out.println( getValue( Action.NAME ) );
        public static void main(String[] args)
            KeyboardAction frame = new KeyboardAction();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }Here is section in the Swing tutorial that explains more about key bindings and Actions:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html

  • JMenu and MouseListener problems

    I have a JMenu that is used as a JMenuItem in another JMenu in the menu bar. The same JMenu is added as a popup menu to a button.
    I added a MouseListener to the JMenu because I want to execute some code upon mouseEntered() and mouseExited().
    Problem: the listener is only fired when I enter or exit the menu from the menu bar, never when the popup menu of the button is entered or exited.
    What can I do to trigger the mouse listener?

    I have a JMenu that is used as a JMenuItem in another JMenu in the menu bar.Components can only have a single parent. I don't know how what you are describing is possible.
    If you want to share the ActionEvent then you should be using an Action when creating the menu. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html]How to use Actions.
    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 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.

  • A question about ActionListener and MouseListener

    Hi,
    my question here is when we should implement a MouseListener and when we should use ActionListener instead.
    I know ActionEvent is fired when a action performed, for instance, a button was pressed down, but I think by implementing a MouseListener, we can use its mouseClicked(MouseEvent e) method to do the same job as the actionPerformed method.
    So, what's the difference between a actionevent(button has been pressed down)and a mouse event(click on a button)? And when we should use them?

    Using the ActionListener actionCommand is the normal paradigm for button clicks.
    ActionEvents, ChangeEvents etc are much higher-level than MouseEvents. And you should use the highest level of abstraction that provides sufficient specificity.
    When adding MouseListener to an component you actully let the system do more work then needed.
    ( you have the mouseEntered, mousePressed, mouseClicked, mouseReleased, ..)
    Every button click will "generate" three mouse events... pressed, released and clicked.
    good luck!

  • JMenuItem and JPanel issues!

    I have a JMenuBar set up for my program and I want each JMenuItem to show a seperate JPanel when clicked. I've tried container.add(panel1); and panel1.setVisible(true); // (Previously set to false) but neither work.
    This is how I've implemented it:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class LibraryGUI extends JFrame {
         private Container container;
         private JPanel addStaffPanel, addStudentPanel;
         private JLabel addStaffTitle, addStudentTitle;
         // Set up GUI
         public LibraryGUI() {
              super("Visual Library 2.0");
              container = getContentPane();
              // Main menu items
              JMenu fileMenu = new JMenu("File");
              JMenu addMenu = new JMenu("Add");
              JMenu removeMenu = new JMenu("Remove");
              JMenu displayMenu = new JMenu("Display");
              // Set up 'File' menu items
              JMenuItem exit = new JMenuItem("Exit");
              // Set up 'Add' menu items
              JMenuItem addStaff = new JMenuItem("Add Staff Member");
              JMenuItem addStudent = new JMenuItem("Add Student Member");
              // Set up the 'File' menu
              fileMenu.add(exit);
              // Set up the 'Add' menu
              addMenu.add(addStaff);
              addMenu.add(addStudent);
              // Create menu bar and attach it to the window
              JMenuBar bar = new JMenuBar();
              setJMenuBar(bar);
              // Add menu's to the menu bar
              bar.add(fileMenu);
              bar.add(addMenu);
              // File --> Exit (THIS WORKS FINE!)
              exit.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        System.exit(0);
              // Set up 'Add Staff Member' title
              addStaffTitle = new JLabel();
              addStaffTitle.setText("Add Staff Member");
              // Set up 'Add Student Member' title
              addStudentTitle = new JLabel();
              addStudentTitle.setText("Add Student Member");
              // Set up 'Add Staff Member' panel
              addStaffPanel = new JPanel();
              addStaffPanel.setLayout(new GridLayout(1,1));
              addStaffPanel.add(addStaffTitle);
              // Add --> Add Staff Member (THIS DOESN'T WORK)
              addStaff.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        container.add(addStaffPanel);
              // Set up 'Add Student Member' panel
              addStudentPanel = new JPanel();
              addStudentPanel.setLayout(new GridLayout(1,1));
              addStudentPanel.add(addStudentTitle);
              // Window settings
              container.setBackground(Color.WHITE);
              setSize(600, 400);
              setVisible(true);
         public static void main(String args[]) {
              LibraryGUI application = new LibraryGUI();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }It compiles fine, no errors. But when the menu items are clicked it just does nothing. Any ideas?
    - Will

    Hmm, normally after adding/remove component to/from a panel you would need to use panel.revalidate. However, this didn't seem to work. Playing around I came up with the following:
    container.setVisible(false);
    container.removeAll();
    container.add(addStudentPanel);
    container.setVisible(true);
    However, instead of using this approach I suggest you look at using a CardLayout. This Layout Manager was designed for this situation, to replace the entire contents of a panel with multiple different panels. Read this section from the Swing tutorial on Using Layout Managers:
    http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html
    An added bonus when using the CardLayout is that you can share the same ActionListeners for all panels. When adding a panel to the CardLayout you need to give a name to the panel (eg. "staff", "student"). When you create your menu items you can use the setActionCommand(...) method:
    addStaff.setActionCommand("staff");
    addStudend.setActionCommand("student");
    Now in your action listener you would just use the event.getActionCommand() method to determine which card panel to display.

  • 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

  • JTable and MouseListener

    Hi,
    I am using JSDK 1.3.
    I am seeing some unpredictable behavior when using MouseListener on JTable.
    Here's the problem:
    When I click on row in the table, I am expecting that every time there is a click, application would process mouseClicked() event. However it does not always happen. I would say the event is not being fired about 5-10% of the time. I don't play with mouse listener during table selection. The mouse listener is added only once when seeting up the GUI.
    Does anybody know if this is a bug with Java?
    Thanks,
    Boris

    Hi, I'm a newbie and no expert in this, but I've had to deal with mouse listeners a lot in the past days. Apparently, those are known issues in Java, and sometimes you have to click twice in order to reset the mouse. Take a look at this, hope it helps:
    http://www.javaworld.com/javaworld/javaqa/2000-07/02-qa-0714-mouse.html
    Best,
    Marina.

  • JMenu,JMenuItems and JRadioButtonMenuItem

    Hi I have a JMenu in the JMenuBar.I have a JMenu in it and Then I have 6 JMenuItems which are Of the JRadioButtonMenuItems.
    I need to get on of it selected manually .Can somebody help me in this.I am able to get the name if the MenuItems but I am not able to get it selected.
    Thanks in advance.

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

  • JSpinner and MouseListener for EzCalendar

    hi,
    has anybody succesfully set a MouseListener to a JSpinner? I've tried to set it to the Spinner directly, to it's Editor, even to the underlying Component, but my MouseListener is never activated. It seems the JSpinner consumes all the mouse events itself without passing them on.
    Background: I'd like to catch right-button clicks on a JSpinner.DateEditor to pop up the EzCalendar which was discussed her recently.
    Any ideas are welcome...
    Klaus

    FYI:
    ((JSpinner.DefaultEditor) mySpinner.getEditor()).getTextField.addMouseListener(myMouseListener);dit it. The MouseListener had to be added to the underlying FormattedTextField. Duh!

  • Asking about icon and mouselistener

    i think i post this thread before but it was gone. so i post it again.
    anybody knows how to insert icon in JFrame? so far, it can only implemented in JPanel. and somebody help me how to make icon larger than before and show some tooltip when mouse select it? in my mind, we just add listener when mouse over image, then setTooltips. is it right?

    i think i post this thread before but it was gone. so i post it again. Quit cluttering the forum with multiple postings and learn how to use the forum properly.
    You can find you postings by:
    a) displaying your "Watch List" which can be found on the left of the forum when you are logged in
    b) searching the forum for any posting that contains your userid
    Also, Swing related questions should be posted in the Swing forum, but there is no need to create a third posting because you already got an answer in your first posting so all you need to do is find it.

  • How can I distinguish a JMenuItem , JPopupMenu and TopLevelMenu?

    I used the following methods to get the component who (a menu)gains the focus:
    JComponent com = JFrmame.getFocusOwner();
    or
    MenuSelectionManager menuMgr = MenuSelectionManager.defaultManager();
    MenuElement[] menuPath = menuMgr.getSelectedPath();
    if(menuPath != 0) {
    JComponent comp = Array.get(menuPath, menuPath.length-1); // this is the item with the focus
    then I need to use getAction() to get the menuItem's action. But how can I filter JMenuItem and JPopUpMenu from TopLevelMenu (JMenuBar item) ?
    Thanks!

    The instanceof may provide the simplest solution, since JPopupMenu, JMenuBar and JMenuItem don't have any kind of ancestor relationship with each other.if (comp instanceof JPopupMenu) {
        // Popup
    } else if (comp instanceof JMenuItem) {
        // Item
    } else if (comp instanceof JMenuBar) {
        // Bar
    } else ...?Hope this helps,
    -Troy

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

  • Jmenuitem overlap with jchoice on a panel

    my jmenuitem ovelap with jchoice panel and look like the jmenuitem is at the back of the jchoice on a panel . is this a bug? how to overcome this?

    i think is because my jmenuitem and panel is swing component and my jchoice is awt component? can this be the reason? how to overcome this?

Maybe you are looking for

  • ITunes external drive- how to sync

    I have a macbook and because the hard drive is only 150GB, I've always had my iTunes music on an exernal drive. I had to blow away the OS and rebuild it because of some problems and now, I can't get my music to show up in itunes. I've changed the med

  • Cant copyépaste a file in the right folder

    I am new in MAC but am confused. When I copy a file from a HD to another specifying a folder and sub-folder in that folder, in reality the file is not stored in that sub-folder. It goes right to the root directly of the HD. What have I done wrong to

  • Cant burn discs and warning message

    My computer wont burn discs. It recognizes and imports music and recognizes blank discs but it says disc recording not found when i try and burn it. It also has a warning message when i open itunes that says "the registry settings used by itunes driv

  • Remittance Advice Forms using (AU_BECS_B) PMW

    Hi Friends, We are deploying BCM for our client. In the process we are migrating from Classic Payment Medium to Payment Medium using PMW (AU_BECS_B) While creating payment method in the company code (FBZP)I dont see any field for form data (next form

  • Im connected to the internet but itunes says im not

    I updated my 4 last night to 6.0 through icloud and this morning it has the cord and the itunes logo on the screen. I tried to plug it in to my PC and it tells me that there is no internet connection, so I restarted my PC plugged my 4 back in and it