java - How to refactor inner class MouseAdapter? -


suppose have file this:

import javax.swing.jpanel; import java.awt.event.mouseadapter; public class foo extends jpanel {     private int m;     private int n;     private int o;      public foo()     {         this.addmouselistener(new bar());     }      class bar extends mouseadapter     {         // ...         // methods here access , modify values of private         // instance variables.         // ...     } } 

obviously can add simple accessors , mutators foo gets tedious fast , breaks encapsulation. how can refactor inner class while keeping damage encapsulation minimum?

if these classes seem big, should split them. first step in splitting them stop relying on private instance variables of outer class. could, say, add public getters , setters, better have foo implement public interface of bar, , have bar talk interface. , initialize each bar self.

public class bar extends mouseadapter {     public interface caller {         void thingclicked();         ...     } }  public class foo extends jpanel implements bar.caller {     ... } 

so in bar have like:

public void mouseup() {    m = m + 1;    n = 0 } 

you have

public void mouseup() {    caller.thingclicked(); } 

and, in foo:

public void thingclicked() {    m = m + 1;    n = 0 } 

it's hard make clear without more specifics, outer class responding messages, , mouse listener responsible delivering messages, not happens in response them. in examples above looks more code have, suspect you'll find slicing out in way leads less code - , code easier test , reuse.


Popular posts from this blog