import javax.swing.*;
import javax.swing.event.*;
public class NewGUIStuff{
public static void main(String args[]){
NewGUIStuff gui = new NewGUIStuff();
gui.go();
}
class handlesListListeners implements ListSelectionListener{
public void valueChanged(ListSelectionEvent lse){
list.setVisibleRowCount(4);
}
}
public void valueChanged(ListSelectionEvent lse){
}
public void go(){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JList list;
String[] aList = {"alpha","beta","gamma","delta","epsilon","zeta","eta","theta"};
list = new JList(aList);
list.addListSelectionListener(new handlesListListeners());
JScrollPane scroller = new JScrollPane(list);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
frame.setContentPane(scroller);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
}
So my question here is if inner classes can see their outer classes variables and objects, why can’t the inner-class handlesListListeners see the list object I made in NewGUIStuff outer class?
Non-static inner classes can see the outer class instance variables and those local variables they were enclosed around (think closures) if those were declared
final(in case of anonymous inner classes). Those non-static inner classes have an implicit reference to the outerthisinserted by the compiler and that’s how they see the member variables of the outer class. The final local variables you enclose your anonymous class around will be implicitly passed into the a constructor that the compiler will generate for you and stored in the final member fields of the inner class itself.In your case I see you expect to see a local variable defined in a whole different lexical context, the one your inner class has no knowledge about. Convert it into the outer class member variable and your inner class will see it.