从字符串创建对象名称



几个小时前我问了这个问题,但我认为我没有很好地解释自己。这是我的代码:

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

---编辑----

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

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

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

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

最新更新