Access outer anonymous class from inner anonymous class

前端 未结 4 1544
孤城傲影
孤城傲影 2021-02-12 23:25

I\'m just curious. Is there a way to access parent in anonymous class that is inside another anonymous class?

I make this example create a JTable subclass

4条回答
  •  星月不相逢
    2021-02-13 00:04

    I think you can create outer reference and use it in your anonymous inner. At least that works for me on JDK 1.7 and JDK 1.8.

    public class Test{
    
            public static void main(String args []){
    
                class Foo extends JTable {
    
                    @Override
                    public void changeSelection(
                        final int row, final int column,
                        final boolean toggle, final boolean extend) {
                        final Foo outer = this; // reference to itself
    
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                outer.changeSelection(row, column, toggle, extend); 
                                //more code here
                            }
                        });
                    }
                };
    
                JTable table = new Foo();
    
            }//end main
    
     }//end test 
    

提交回复
热议问题