是否可以使用选定的 JMenuItem 重命名 JMenu 标题?
我正在使用 ActionListener 来执行此操作:
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;
}
我希望菜单显示Pink
而不是Choose Bow:
,但我现在写的只是在菜单栏上重新创建一个新菜单,除了我的菜单之外已经有了。
最佳答案
这个:
JMenu 菜单 = new JMenu(name);
需要更改为:
menu = new JMenu(name);
其中 menu
是该类的实例成员:
私有(private) JMenu 菜单;
然后在 actionPerformed(...)
中,只需调用:
menu.setText(current)
而不是重新创建它。
关于Java Swing : renaming JMenu title based upon JMenuItem selection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23664534/