从String创建对象名称

时间:2012-09-01 01:07:00

标签: java swing events actionlistener jmenuitem

几个小时前我问question这个问题,但我想我没有解释好自己。 这是我的代码:

for (a = 1; a < 14; a++) {
    JMenuItem "jmenu"+a = new JMenuItem(String.valueOf(a));
    "jmenu"+a.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            rrr[a] = a;
            texto.setFont(texto.getFont().deriveFont((float) a));
            current = a;
        }
    });
    tamano.add("jmenu"+a);
}

我需要做的是使用以下名称创建几个JMenuItem

jmenu1
jmenu2
jmenu3
jmenu4
etc... 

--- ---- EDIT

我想要的是每个JMenuitem都有不同的名称:

JMenuItem "jmenu"+a  //with this I can't create the JMenuItem; it's not permitted
  = new JMenuItem(); //I dont care about this

2 个答案:

答案 0 :(得分:9)

您无法以编程方式命名变量。如果你想要14个不同的组件,那么创建一个数组或List来保存这些组件,然后在循环中创建这些组件并将它们添加到你的数组/列表中。如果你想要第n个组件,你可以使用components [n]或list.get(n)来获取它。

答案 1 :(得分:4)

这里有2个问题

第一个是构建JMenuItem数组

JMenuItem[] menuItems = new  JMenuItem[14];  
for (int a = 1; a < 14; a++) {
    menuItems[a] = new JMenuItem(String.valueOf(a));
    menuItems[a].addActionListener(new MenuItemAction(a));
    tamano.add(menuItems[a]);
}

第二个是使用ActionListener中的值。因为每个菜单都有自己的关联值,所以具体类优于匿名类:

class MenuItemAction extends AbstractAction {
    private final int associatedValue;

    public MenuItemAction(int associatedValue) {
       this.associatedValue = associatedValue;
    }

    public void actionPerformed(ActionEvent e) {
       JMenuItem menuUtem = (JMenuItem)e.getSource();
       System.out.println(associatedValue);
       // do more stuff with associatedValue
   }
}