Reputation: 9
Whenever I try to compile the program, I get the error "local variable iteration defined in an enclosing scope must be final or effectively final". Does anyone know how to fix this? The code is not completed yet, so some things may seem out of place.
public static void go(purchase joe) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpinnerNumberModel NumberImput =
new SpinnerNumberModel(1.00,0.00,null,1.00);
int iteration = 0;
JSpinner spinner = new JSpinner(NumberImput);
JLabel label = new JLabel("Please enter the price of the Item.");
JButton button = new JButton("Press here to continue");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
switch (iteration) {
case 0:
joe.setPrice((double)NumberImput.getNumber());
label.setText("Plese enter the amount that you are buying");
NumberImput.setValue(1.00);
iteration += 1;
break;
case 1:
joe.setAmount((int)NumberImput.getNumber());
label.setText("Plese enter the amount that you are buying");
break;
}
}
});
frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(spinner);
frame.add(button);
frame.setSize(600, 500);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
joe.setPrice((double)NumberImput.getNumber());
}
Upvotes: 0
Views: 173
Reputation: 109547
You are using iteration += 1;
. This is an assignment to a local variable.
Now the ActionListener object lives longer than the local variable; actionPerformed may be called after the method's call disappeared.
For this reason the Java Virtual Machine adds a new variable iteration
to the ActionListener, a copy. To prevent that assigning to the local variable iteration
would make the other iteration
stale, the language decided that the local variable must be constant, not assigned to, "effectively final."
AtomicInteger iteration = new AtomicInteger();
... iteration.getAndIncrement();
However as actionPerformed
is called later, just remove iteration
.
You could use a field in ActionListener.
button.addActionListener(new ActionListener() {
int iter;
@Override
public void actionPerformed(ActionEvent e) {
switch (iter) {
case 0:
joe.setPrice(NumberImput.getNumber().doubleValue());
label.setText("Please enter the amount that you are buying");
NumberImput.setValue(1.00);
iter++;
break;
case 1:
joe.setAmount(NumberImput.getNumber().intValue());
label.setText("Please enter the amount that you are buying");
break;
}
}
});
On style: always use @Override
as you will capture typos in similar cases.
@Override
public void actionPerformed(ActionEvent e){
Use numberInput
; variables, fields and methods starting with a small letter.
Upvotes: 0