swing - DRY code to implement action listener (JAVA) -


i'm implementing tray game, in use jbutton represent tray. tray makes 7x7, implement action listener it's not fun. have code :

public void actionperformed(actionevent ae)      {         if (ae.getsource() == bouton11)             {                 this.posepion(1, 1, bouton11);             }             else if (ae.getsource() == bouton21)             {                 this.posepion(2, 1, bouton21);             }             else if (ae.getsource() == bouton31)             {                 this.posepion(3, 1, bouton31);             }             ......     } 

how can reduce sort of code please ? :/

thank :)

make own listener type. type should implement actionlistener (and actionperformed method), , constructed 3 parameters: button , 2 integers. reason why need these 3 parameters can pass them posepion method (which should capitalized posepion, way).

for example:

class poseactionlistener implements actionlistener {      private jbutton button;     private int a, b;      public poseactionlistener(jbutton btn, int a, int b) {         this.button = btn;         this.a = a;         this.b = b;     }      @override     public void actionperformed(actionevent e) {         posepion(a, b, btn);     } } 

then:

button11.addactionlistener(new poseactionlistener(button11, 1, 1); button12.addactionlistener(new poseactionlistener(button12, 1, 2); 

or, better, create buttons @ once:

for (int i=1; i<=7; i++) {     (int j=1; j<=7; j++) {         jbutton btn = new jbutton("button " + + ", " + j);         // store button in array if want         btn.addactionlistener(new poseactionlistener(btn, i, j);     } } 

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -