Rectangle 27 0

I have found just by using frame.setJMenuBar(jmenubar); where frame is your JFrame and jmenubar is your JMenuBar, it'll automatically do this. You don't even have to add it to your layout manager.

java - Focus on first jmenubar item on "alt" key press - Stack Overflo...

java swing jmenu jmenubar alt-key
Rectangle 27 0

One thing I attempted is to simply call setSelected(false) from within the menuSelected(...) method, but this has side effects. For one, the menu doesn't appear to be selected, and for another, it doesn't work all the time.

One possible solution that does work is to deselect the menu in a Swing Timer. Something like:

Interesting approach... more work to do I'd have to use Timer... I'll try and I'll give a feedback. Thanks.

Sorry... didn't work either. But there might be a solution... They didn't make available such Event without thinking how-to work around this issue.

@LucDaher: It works fine for me in my test program. If it didn't work for you, then you should create a small compilable and runnable test program that shows this, and also allows us to see and experience your necessary conditions.

I discovery what is the problem and, perhaps, it has worked for you because you might use any Microsoft Windows OS (or some OS different than Linus with Gnome GTK+ as Window Manager). I've forgot to mention that the underlying OS where my test environment lies is Ubuntu and I'm using Gnome GTK+ as my default Look And Feel. As soon I've tested over my guest WinXP virtualbox and set the L&F as "Window", using your suggestion (or simply exitMenu.setSelected(false)) , it worked flawlessly. Note: I tried with Metal L&F on the WinXP and it's not worked as well, only with Window (or Classic) L&F.

swing - Java JMenu - Selected and Deselected feature - Stack Overflow

java swing selected jmenu
Rectangle 27 0

This is the expected polymorphic behavior. The isSelected() method of JMenuItem is inherited from AbstractButton, while the same method in Jmenu is overridden so that it "Returns true if the menu is currently selected (highlighted)."

so, what can i do? :S

@trashgod so from what you are saying and what @Nika Gamkrelidze want I think the OP should set Actions on the JMenuItems to detect when they are selected, right? BTW +1.

It depends on what you want to do and how much you want to do it. JMenu has a private ChangeListener that invokes both fireMenuSelected() and fireMenuDeselected(); you could override them and see what turns up.

@Boro: Thanks! Action would be preferred, but menus don't honor the selected property. I can see wanting to do something as the user rolls over each JMenuItem; I'm less sanguine about JMenu.

java - Why my ChangeListener reacts only for JMenu, and not for JMenuI...

java swing jmenu jmenuitem changelistener
Rectangle 27 0

The problem is that MenuSelectionManager is already cleared when your actionPerformed is invoked.

The calls are put in that order:

msm.clearSelectedPath(); // msm is the MenuSelectionManager
    menuItem.doClick(0); // This eventually triggers your actionPerformed

But the question is what are you trying to do with that? You obviously know on which JMenutItem the click was performed (e.getSource() returns the related JMenuItem), and you can easily travel back up the component hierarchy to retrieve the complete path of the selected menu, so I wonder what you are trying to achieve with such code.

Many thanks, I need to know the entire path of the JMenu clicked to reached the JMenuItem. Could you please tell me how to travel back up the component hierarchy to retrieve the complete path of the selected JMenuItem?

((JMenutItem)a.getSource()).getParent();
JMenu
JMenuBar

java - swing JMenu retrieve path of a selected item - Stack Overflow

java swing jmenu
Rectangle 27 0

You have initialized the JFileChooser but you didn't show the dialog. You must call the appropriate method to display:

int returnVal = chooser.showOpenDialog(parent);
int returnVal = chooser.showSaveDialog(parent);

where should i put it? im sorry i'm new and i just heard the jfilechooser for enhancement of my program

java - JFileChooser does not appear when JMenu is selected - Stack Ove...

java swing jfilechooser jmenu
Rectangle 27 0

One way to accomplish this would be to create a button that when clicked shows a JPopupmenu, just below the button. The menu would allow the user to select from the menu or submenu. The label/selection of the original button should be changed when a menu item is selected.

java - JComboBox that is a Menu - Stack Overflow

java swing jcombobox jmenu
Rectangle 27 0

I am not entirely sure where, but an invokeLater is probably needed. This does the heavy work a bit later, and allows the event queue thread to handle all events, like the button click fast and keep responsive and reactive - as with menus being enabled.

jMenu bar in Java Swing not enabling issue - Stack Overflow

java swing jmenu jmenubar
Rectangle 27 0

If you only want numbers then the two common approaches are:

a) use a JFormattedTextField.

b) add a DocumentFilter to the Document of the text field.

Both approaches are explained more in the Swing tutorial. See the sections on "How to use Formatted Text Fields" and "Text Component Features (Implementing a Document Filter)".

swing - Java JMenu and Jtextfield that only handles numbers not string...

java swing jtextfield actionlistener jmenu
Rectangle 27 0

I changed the file a little bit to show the file open dialog after selecting the open menu. What do you use for development? Just try NetBeans. It's much easier with an IDE to create useful user interfaces.

Here is what i did based on your code:

package hw;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class Myprog extends JFrame {

    JMenuBar hard = new JMenuBar();
    JMenu file = new JMenu("FILE");
    JMenuItem open = new JMenuItem("Open");
    JMenu histo = new JMenu("History");
    JMenuItem exit = new JMenuItem("Exit");
    JMenu view = new JMenu("VIEW");
    JMenu descript = new JMenu("Description");
    JMenu spm = new JMenu("Specs/Model/Version");
    JMenu extra = new JMenu("EXTRAS");
    JMenu trans = new JMenu("Transaction");
    JMenu calcu = new JMenu("Calculator");
    JMenu qoutes = new JMenu("Quotes");
    JMenuItem game = new JMenuItem("Games");
    JMenu about = new JMenu("ABOUT");
    JMenuItem java = new JMenuItem("JAVA");
    JMenuItem sirjet = new JMenuItem("References");
    JMenuItem akoto = new JMenuItem("MyProfile");
    JMenuItem mouse = new JMenuItem("Mouse");
    JMenuItem cpu = new JMenuItem("CPU");
    JMenuItem cam = new JMenuItem("Camera");
    JMenuItem key = new JMenuItem("Keyboard");
    JMenuItem mem = new JMenuItem("Memory");
    JMenuItem mic = new JMenuItem("Microphone");
    JMenuItem print = new JMenuItem("Printer");
    JMenuItem scan = new JMenuItem("Scanner");
    JMenuItem speak = new JMenuItem("Speaker");
    JMenuItem mon = new JMenuItem("Monitor");
    JFileChooser choosyAko = new JFileChooser(".");

    JLabel direct = new JLabel(" ");
    JLabel filename = new JLabel(" ");

    public Myprog() {
        super("My Program(Hardware)");
        setBounds(250, 250, 700, 700);
        setBackground(Color.GREEN);
        direct.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36));
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setJMenuBar(hard);
        hard.add(file);
        file.setMnemonic('F');
        file.add(open);
        open.setMnemonic('O');
        file.add(histo);
        histo.setMnemonic('H');
        histo.add(cam);
        histo.add(cpu);
        histo.add(key);
        histo.add(mem);
        histo.add(mic);
        histo.add(mon);
        histo.add(mouse);
        histo.add(print);
        histo.add(scan);
        histo.add(speak);
        file.add(exit);
        exit.setMnemonic('X');
        hard.add(view);
        view.setMnemonic('V');
        view.add(descript);
        descript.setMnemonic('D');
        view.add(spm);
        spm.setMnemonic('S');
        hard.add(extra);
        extra.setMnemonic('E');
        extra.add(trans);
        trans.setMnemonic('T');
        extra.add(calcu);
        calcu.setMnemonic('C');
        extra.add(qoutes);
        qoutes.setMnemonic('Q');
        extra.add(game);
        game.setMnemonic('G');
        hard.add(about);
        about.setMnemonic('B');
        about.add(java);
        java.setMnemonic('J');
        about.add(sirjet);
        sirjet.setMnemonic('N');
        about.add(akoto);
        add(direct, BorderLayout.NORTH);
        add(filename, BorderLayout.SOUTH);
//        add(choosyAko, BorderLayout.CENTER);

        open.addActionListener(new open());
        exit.addActionListener(new exit());
    }

    class open implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JFileChooser choosyAko = new JFileChooser(".");
            JLabel direct = new JLabel(" ");
            JLabel filename = new JLabel(" ");
            choosyAko.setControlButtonsAreShown(false);
            choosyAko.showOpenDialog(null);
        }
    }

    class exit implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    }

    public static void main(String[] args) {
        Myprog frame = new Myprog();
        frame.setVisible(true);
    }
}

java - JFileChooser does not appear when JMenu is selected - Stack Ove...

java swing jfilechooser jmenu
Rectangle 27 0

What you want to do is add a ChangeListener to the JMenuItem and check if it's selected or armed and change the icon accordingly. The ChangeListener works for both keyboard and mouse.

private JMenuItem createMenuItem(final ImageIcon icon, String title) {
    JMenuItem item = new JMenuItem(title);
    item.setIcon(icon);

    ChangeListener cl = new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            if (e.getSource() instanceof JMenuItem) {
                JMenuItem item = (JMenuItem) e.getSource();
                if (item.isSelected() || item.isArmed()) {
                    item.setIcon(stackIcon);
                } else {
                    item.setIcon(icon);
                }
            }
        }
    };
    item.addChangeListener(cl);

    return item;
}

Here is running example. Just replace images with yours

import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class RolloverMenuItem {
    ImageIcon stackIcon = new ImageIcon(getClass().getResource("/resources/stackoverflow2.png"));

    public RolloverMenuItem() {
        ImageIcon newIcon = new ImageIcon(getClass().getResource("/resources/image/new.gif"));
        ImageIcon saveIcon = new ImageIcon(getClass().getResource("/resources/image/open.gif"));
        ImageIcon openIcon = new ImageIcon(getClass().getResource("/resources/image/save.gif"));

        JMenu menu = new JMenu("File");
        menu.setMnemonic(KeyEvent.VK_F);
        JMenuItem item1 = createMenuItem(newIcon, "New");
        JMenuItem item2 = createMenuItem(openIcon, "Open");
        JMenuItem item3 = createMenuItem(saveIcon, "Save");
        menu.add(item1);
        menu.add(item2);
        menu.add(item3);

        JMenuBar menuBar = new JMenuBar();
        menuBar.add(menu);

        JFrame frame = new JFrame("Rollover MenuItem");
        frame.setJMenuBar(menuBar);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 250);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JMenuItem createMenuItem(final ImageIcon icon, String title) {
        JMenuItem item = new JMenuItem(title);
        item.setIcon(icon);

        ChangeListener cl = new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                if (e.getSource() instanceof JMenuItem) {
                    JMenuItem item = (JMenuItem) e.getSource();
                    if (item.isSelected() || item.isArmed()) {
                        item.setIcon(stackIcon);
                    } else {
                        item.setIcon(icon);
                    }
                }
            }
        };
        item.addChangeListener(cl);

        return item;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new RolloverMenuItem();
            }
        });
    }
}

java - How to change icon for JmenuItem on rollover - Stack Overflow

java swing rollover jmenu jmenuitem
Rectangle 27 0

  • Menu - A parent JMenu cannot be selected. Why would you want to know if the mouse is over it?
  • MenuItem - Embrace the Action interface

It is an all too common oversight to not use the Action interface. When developing with Swing make Action your friend, it will treat you well. You went down the wrong path with MenuSelectionManager.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class MenuExample {
    private JFrame frame;
    private JLabel choiceIndicator;

    MenuExample create() {
        frame = createFrame();
        choiceIndicator = new JLabel();
        frame.setJMenuBar(createMenuBar());
        frame.getContentPane().add(createContent());

        return this;
    }

    private Component createContent() {
        JPanel panel = new JPanel();

        panel.add(new JLabel("Last menu item choice:"));
        panel.add(choiceIndicator);

        return panel;
    }

    private JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(createWorld());
        return menuBar;
    }

    private JMenu createWorld() {
        JMenu worldMenu = new JMenu("World");

        worldMenu.add(createIndia());
        worldMenu.add(new JMenu("Australia"));
        worldMenu.add(new JMenu("America"));

        return worldMenu;
    }

    private JMenu createIndia() {
        JMenu india = new JMenu("India");

        india.add(createOdisha());
        india.add(new JMenu("Delhi"));
        india.add(new JMenu("Uttar Pradesh"));
        india.add(new JMenu("Madhya Pradesh"));

        return india;
    }

    private JMenuItem createOdisha() {
        JMenu menu = new JMenu("Odisha");

        menu.add(createBhubaneswar());
        menu.add(new JMenu("Berhampur"));

        return menu;
    }

    private JMenuItem createBhubaneswar() {
        JMenu menu = new JMenu("Bhubaneswar");
        menu.add(choiceItem("Raj Mahal"));
        menu.add(choiceItem("Acharya Bihar"));
        menu.add(choiceItem("Bani Bihar"));

        return menu;
    }

    private JMenuItem choiceItem(String text) {
        return new JMenuItem(new Choice(text, choiceIndicator));
    }

    private JFrame createFrame() {
        JFrame frame = new JFrame(getClass().getSimpleName());
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        return frame;
    }

    void show() {
        frame.setSize(350, 250);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MenuExample().create().show();
            }
        });
    }

    class Choice extends AbstractAction {
        private final JLabel choiceIndicator;

        public Choice(String text, JLabel choiceIndicator) {
            this(text, null, null, null, choiceIndicator);
        }

        public Choice(String text, ImageIcon icon, String desc, Integer mnemonic, JLabel choiceIndicator) {
            super(text, icon);
            putValue(SHORT_DESCRIPTION, desc);
            putValue(MNEMONIC_KEY, mnemonic);

            this.choiceIndicator = choiceIndicator;
        }

        public void actionPerformed(ActionEvent e) {
            choiceIndicator.setText(e.getActionCommand());
        }
    }
}

Thanks a lot sir,i will keep in mind all these concepts as mentioned by you .

java - How to get the currently selected Menu or MenuItem - Stack Over...

java swing jmenu jmenuitem jmenubar
Rectangle 27 0

If you are using the Swing Actions the components should be disabled/enabled automatically if the action itself is. You can register yourself as a propertyListener to an action as well to monitor other changes. Look at http://java.sun.com/javase/6/docs/api/javax/swing/Action.html for detailed list of which properties are available.

java - Sync JMenu ButtonGroups with JToolbar ButtonGroups - Stack Over...

java swing menu toolbar action
Rectangle 27 0

Ok, there are a few issues with your code, but I'll go over the two specifics that answer your question:

1) You're not adding your action listener to any of your MenuItems in your code. When I added your handler to the MenuItems using addActionListener(handler); It started triggering.

2) You're adding handler as the actionListener to two buttons that are invisible (and you've got other layout issues)

Sorry about that I had the action listeners previously I just forgot to re-add them to the MenuItems. I am aware of the buttons that are invisible as well. But the problem is that when I declare my JMenu items at class level, and try to add action listeners to them for some reason I get an error.

Wait, are you still seeing an error? What error are you seeing?

java - JMenu Item Action Listener is not being detected - Stack Overfl...

java swing actionlistener jmenu jmenuitem
Rectangle 27 0

  • Set the text box to not editable. Add a listener to your selection and when a currency is selected set the textbox to editable.
  • Use a JFormattedTextField to prevent un-wanted formats.

swing - Java JMenu and Jtextfield that only handles numbers not string...

java swing jtextfield actionlistener jmenu
Rectangle 27 0

If we want to trigger an event by the JMenu component in the JMenuBar, we should try changing it and adding JBUtton to the JMenuBar instead of JMenu. Because JMenu is not supposed to be used this way. Although, if you have a JMenuItem inside that JMenu, then you can trigger an event and handle it appropriately.

Or you should use a JToolBar to add JButtons to as that is the expected user experience, no one expects to find anything other then menu's on a menu bar...

java - JMenu remains selected after a mouse click - Stack Overflow

java swing jmenu
Rectangle 27 0

Thanks. But it does seem like an awful lot of refactoring required in order to apply this pattern. It seems that if I did this I'd have to code specifically for each of the items. I was hoping that there is a smarter way to determine this automatically given that the menu items and the toolbar items share the same actions.

java - Sync JMenu ButtonGroups with JToolbar ButtonGroups - Stack Over...

java swing menu toolbar action
Rectangle 27 0

"(JTable)popup.getInvoker();" which unfortunately does not work with JMenuItems.

You are already using the getParent() method. You just can't assume that the JPopupMenu is the first parent.

You need to create a while loop that keeps getting the parent of the menu item until you find the popup menu. Then you can access the invoker.

thanks. I've tried the loop but I'm getting Null Pointer on the different levels of .getParent().

Get selected cell rows from nested JMenuItems context menu (Java Swing...

java swing jtable jmenu jmenuitem
Rectangle 27 0

Credits to @camickr and this post on parent frame of JMenuItem. Here's what works (code for illustration):

@Override
public void actionPerformed(ActionEvent e) {
    JMenuItem source = (JMenuItem)(e.getSource());
    try{
        JMenuItem menuItem = (JMenuItem) e.getSource(); 
        JPopupMenu popupMenu = (JPopupMenu) menuItem.getParent(); 
        Component invoker = popupMenu.getInvoker();      
        JPopupMenu popup = (JPopupMenu) invoker.getParent();
        JTable table = (JTable)popup.getInvoker();
        int row[] = table.getSelectedRows();
        int col[] = table.getSelectedColumns();
        System.out.println("Test print: "+row[0]+"-"+col[0]);
    }catch(Exception ex){
        ex.printStackTrace();
    }
}

Using jMenu.setName("jMenu1") and source.getParent().getName() and was helpful in debugging.

Get selected cell rows from nested JMenuItems context menu (Java Swing...

java swing jtable jmenu jmenuitem