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);
}
Java methods are not first-class objects (or second or third-class objects; in fact, methods are not objects at all). You need to move the method into one of the classes – either your top class, or the anonymous inner class that you defined, like this: