declaring a "final" variable?
Hi, I need help with my homework.
I'm getting an error along the lines of "local variable names needs to be declared final", first in line 50.
Code :
// Author: Blake Needleman
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HW9_2 extends JFrame {
private JLabel user = new JLabel("Username:");
private JTextField username = new JTextField("");
private JLabel pass = new JLabel("Password:");
private JTextField password = new JTextField("");
private JLabel in = new JLabel("Logged in.");
private JLabel notIn = new JLabel("Not logged in.");
private JButton login = new JButton("Login");
private JButton logout = new JButton("Logout");
public static void main(String[] args) {
HW9_2 myFrame = new HW9_2();
myFrame.setVisible(true);
myFrame.setTitle("Login");
myFrame.setSize(300, 200);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public HW9_2() {
setLayout(new GridLayout(3, 2, 5, 5));
add(user);
add(username);
add(pass);
add(password);
add(notIn);
add(login);
String[] names;
names = new String[2];
names[0] = "Ann";
names[1] = "Bob";
String[] codes;
codes = new String[2];
codes[0] = "apple";
codes[1] = "blueberry";
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = username.getText();
String passWord = password.getText();
int winning_position;
for (int i = 0; i < names.length; i ++) {
if(name.equals(names[i])) {
winning_position = i;
}
}
if (passWord.equals(code[winning_position])) {
login.setText(logout + "");
notIn.setText(in + "");
}
}
});
}
}
Any ideas?
Re: declaring a "final" variable?
You're trying to access a local variable within an anonymous inner class.
Either Initialise String[] names as an instance variable or say:
final String[] names;
Hope this helped.
Edit: Didn't see post date :L