Question

Is it possible to rename the JMenu title using the selected JMenuItem?

I am using an ActionListener to do this:

public MenuBar(){
.
.
.
add(createMenu("Choose Bow: "));
.
.
.
public JMenu createmenu(String name){
JMenu menu = new JMenu(name);
JRadioButtonMenuItem bow = new JRadioButtonMenuItem("Pink");
bow.setHorizontalTextPosition(JMenuItem.RIGHT);
bow.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt){
        String current = "Pink";
        add(createMenu(current));
        menu.revalidate();          
        }
    });

group.add(bow);
.
.
.
menu.add(bow);
menu.revalidate();

return menu;
}

I want the menu to say Pink instead of Choose Bow: but what I have written right now just keeps recreating a new menu on the MenuBar in addition to what I've already got.

Was it helpful?

Solution

This:

JMenu menu = new JMenu(name);

needs to change to:

menu = new JMenu(name); where menu is an instance member of the class:

private JMenu menu;

Then in actionPerformed(...), simply call:

menu.setText(current) instead of re-creating it.

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