2012-09-01 180 views
2

几个小时前我问这个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 S:

jmenu1 
jmenu2 
jmenu3 
jmenu4 
etc... 

---编辑----

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

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

您的意图是什么?你为什么想给你的变量命名? – whirlwin

回答

9

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

+0

这应该是被接受的答案。 – whirlwin

+0

该清单应该是这样吗? JMenuItem [] menues = new JMenuItem [14]? –

+0

@BladimirRuiz就是这样的。确切地说,这是一个数组(不是一个列表)。 – JimN

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 
    } 
}