I know that local variables are not allowed to use within the inner classes. It must be a instance variable or a final one. Someone has said that it is because of the inner class object may exist out of the scope of method.
But I want to know why it is only for InnerClasses. When it is allowed for others. Basically I want to know why Approach 2 is allowed when Approach 1 is not.
Approach 1 :
MainGUI class
private void initializeGUI(){
JTextArea rqJTextArea = new JTextArea();
JTextArea rsJTextArea = new JTextArea();
JButton button = new JButton("Ok"); // http://www.javaprogrammingforums.com/java-swing-tutorials/278-how-add-actionlistener-jbutton-swing.html
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
rsJTextArea.setText(rsJTextArea.getText() + "\n" + rqJTextArea.getText()); // Cannot refer to a non-final variable rsJTextArea inside an inner class defined in a different method
}
});
}
Approach 2 :
MainGUI class
private void initializeGUI(){
JTextArea rqJTextArea = new JTextArea();
JTextArea rsJTextArea = new JTextArea();
JButton button = new JButton("Ok");
SendActionListner sendActionListner = new SendActionListner();
sendActionListner.setRqJTextArea(rqJTextArea);
sendActionListner.setRsJTextArea(rsJTextArea);
button.addActionListener(sendActionListner);
}
SendActionListner class
public class SendActionListner implements ActionListener {
public void actionPerformed(ActionEvent e) {
rsJTextArea.setText(rsJTextArea.getText() + "\n" + rqJTextArea.getText());
}
public JTextArea getRqJTextArea() {
return rqJTextArea;
}
public void setRqJTextArea(JTextArea rqJTextArea) {
this.rqJTextArea = rqJTextArea;
}
public JTextArea getRsJTextArea() {
return rsJTextArea;
}
public void setRsJTextArea(JTextArea rsJTextArea) {
this.rsJTextArea = rsJTextArea;
}
JTextArea rqJTextArea = null;
JTextArea rsJTextArea = null;
}