So, I'm trying to define a set of methods for a large set of buttons, and I figured I could do it in a for loop, but I'm getting a syntax error which I can't decipher... Here's a simplified version of the code I want to use... The error is: "Syntax error on token(s), misplaced construct(s)"
JMenu blocks = new JMenu("Block");
menuBar.add(blocks);
for (int i=0; i < 9; i++){
public void action() {
System.out.println(i+"");
}
JMenuItem blockName = new JMenuItem(i+"");
blockName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
action();
}
});
blocks.add(blockName);
}
intto aStringis not a good practice (since behind the scenes you are creating an unnecessaryStringBuilder). It is rather recommended to useString.valueOf. And anyway,""+iwill output the same result asi+"".