2

I asked this question a few hours ago, but I think I didn't explain myself well. Here is my code:

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

What I need to do is create several JMenuItems with these names:

jmenu1
jmenu2
jmenu3
jmenu4
etc... 

---EDIT----

What I want is that each JMenuitem has a different name:

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

2 Answers2

9

You can't name variables programmatically. If you want 14 different components, then create an array or a List to hold those components, then create those components in a loop and add them to your array/list. If you want the nth component, you can use components[n] or list.get(n) to get it.

JimN
  • 3,120
  • 22
  • 35
4

There are 2 issues here

The first is building up the JMenuItem array

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]);
}

The second is using the values in the ActionListener. Because each menu has its own associated value, a concrete class is better than an anonymous one here:

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
   }
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276