nooby nooby - 3 months ago 16
Java Question

Java actionlistener variable is accessed from within inner class

I'm trying to read from a file when I click my button, but I get

variable is accessed from within inner class
when hovering over the word line.

BufferedReader br = new BufferedReader(new FileReader("OGList.txt"));
String line;


SteamIDBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
while((line = br.readLine()) != null){
System.out.println(line);
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}

Answer

Java forces declaring with the finalmodifier your external variable as used in an inner class. The other solution is declaring your variable directly in the method of the anonymous inner class which needs it
In your case it seems more relevant to declare the line var in the inner class since it's a temporary variable which is modified after the declaration of it.

Besides, you are not forced to declare your BufferedReader var in the inner class, but you can put it too inside. It groups the processing.

SteamIDBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("OGList.txt"));
            String line=null;
            while((line = br.readLine()) != null){
                System.out.println(line);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
Comments