Search code examples
javaswinganonymous-methodsjtoolbar

Accessing "this" from an anonymous Java subclass


I'm trying to modify the behavior of JToolBar to allow it to dock to more than one JPanel. As part of this exercise, I need to override the method getDockingConstraint which I tried to do with an anonymous class using a definition very similar to the original.

The problem is that the original implementation references this several times which I thought would be fine, but I must be missing something because the IDE reports that this.dockingSensitivity is not visible to the anonymous class.

Is there a simple change here, or should I skip this approach and just create a full subclass of BasicToolBarUI? Or maybe there is a better approach entirely to modifying JToolBar's docking capability?

public MultiDockToolBar() {
        setUI(new BasicToolBarUI(){
            @Override
            private String getDockingConstraint(Component var1, Point var2) {
                if(var2 == null) {
                    return this.constraintBeforeFloating;
                } else {
                    if(var1.contains(var2)) {
                        // Breaks here when using this.:
                        this.dockingSensitivity = this.toolBar.getOrientation() == 0?this.toolBar.getSize().height:this.toolBar.getSize().width;
                        if(var2.y < this.dockingSensitivity && !this.isBlocked(var1, "North")) { 
                            return "North";
                        }

                        // Check East
                        // Check West
                        // Check South

                    }

                    return null;
                }
            }
        });
    }

Solution

  • dockingSensitivity is a private field inside BasicToolBarUI class. You will not be able to directly alter this. If you still want to edit and face the potential consequences, you can use Java Reflections library.