2012-09-01 177 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 
    } 
}