Question

I try to make an JMenuBar hide and show with the ctrl+h keystroke, i've succeed to do this for hidding the JMenu but I can't use ctrl+h to show the JMenu, here he's the code :

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;    
import view.Menu;
import view.Window;

public class MenuController implements ActionListener {

    protected Window w;
    protected Menu m;

    public MenuController(Window w) {
        this.w = w;
        this.m = w.getMenu();
        m.getQuit().addActionListener(this);
        m.getHide().addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String item = e.getActionCommand();
        if (item.equals("Quitter"))
            System.exit(0);
        if(item.equals("Masquer le menu")) {
            if(m.isVisible() == true)
                m.setVisible(false);
            else
                m.setVisible(true);
        }
    }    
}

getHide(), give the JMenuItem who have the keystroke, if you see where he's the problem... Regards

Edit : So here, the view.Menu class :

public class Menu extends JMenuBar {

private static final long serialVersionUID = 1L;
private JMenuItem quit = new JMenuItem();
private JMenuItem hide = new JMenuItem();


public Menu() {
    JMenu menu1 = new JMenu("Fichier");

    hide.setText("Masquer le menu");
    hide.setEnabled(true);
    hide.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_MASK));
    menu1.add(hide);

    quit.setText("Quitter");
    quit.setEnabled(true);
    quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK));
    menu1.add(quit);

    add(menu1);
}

public JMenuItem getQuit() {
    return quit;
}

public JMenuItem getHide() {
    return hide;
}

}

Was it helpful?

Solution

Like kleopatra mentioned in the comments, your accelerator won't work if the menu is hidden. If you don't need that key combination for anything else, one way around this problem (a little less dirty, I think, than the tricks mentioned in the link kleopatra posted) would be to register a key binding on the component containing the menu bar that performs the same set of actions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top