java - Alternate displayed image -


i'm doing tictactoe, , idea in first time click 1 button shows image "x" , if click other button shows image "o" ... , continues, showing images alternately. trying 1 click @ button shows 1 image, if click again @ button image disappear.

import java.awt.event.actionevent; import java.awt.event.actionlistener;  import javax.swing.imageicon; import javax.swing.jbutton;   public class xobutton extends jbutton implements actionlistener{   imageicon x;   imageicon o;   byte value=0;   byte k=0;  public xobutton(){     try {         x=new imageicon(this.getclass().getresource("x.png"));         o=new imageicon(this.getclass().getresource("o.png"));         addactionlistener(this);      } catch (nullpointerexception e) {         system.out.println("the image not available");     }  }  @override public void actionperformed(actionevent e) {     value++;     value %= 2;       if( k%2 == 0) {           switch(value){             case 0:                 seticon(null);                 break;             case 1:                 seticon(x);                 system.out.println("kx= " + k);                 break;         }         k++;     }       else {            switch(value){             case 0:                 seticon(null);                 break;             case 1:                 seticon(o);                 system.out.println("k0= " + k);                 break;         }         k++;     }     }  } 

your logic broken, , main problem see each xobutton has own actionlistener, 1 independent of others, , value int equal 0 whenever button pushed first time, regardless of state of pushed buttons.

i suggest

  • you don't extend jbutton rather use jbuttons
  • that give jbutton's same action or actionlistener
  • that listener stores state of xo of last button press
  • that listener checks see if pressed button in null, or x or o state, , acts accordingly.

for example of working tic tac toe program uses image icons, please have @ this answer of mine similar question.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -