i'm trying make own simple memory game , i'm having jpanel implements actionlistener interface , contains tiles inherits jbutton. works fine except fact button being clicked second, not change icon should do. when click 2 tiles match remain flipped , ok. when click 1st button flips on , second pressed tile provided not matching 1 behaves button without actionlistener added. thought fixing problem propertychangelistener can't figure out how.
this method in jpanel :
@override public void actionperformed(actionevent e){ tile tile = (tile)e.getsource(); if(tilesflipped < 2 ){ tile.flip(); flippedtiles[tilesflipped++] = tile; if(tilesflipped == 1){ return; } if(flippedtiles[0].equals(flippedtiles[1])){ tilesflipped = 0; return; } else { try { thread.sleep(1000); for(int = 0; < 2; i++){ flippedtiles[i].flipback(); } } catch (interruptedexception e1) { } } tilesflipped = 0; } } and tile class :
private class tile extends jbutton { string photopath; imageicon photo; tile(int i){ photopath = string.format("/home/stn/desktop/p/9-%d.jpg", i); setpreferredsize(new dimension(150, 150)); this.setbackground(color.cyan); this.photo = new imageicon(photopath); } public void flip(){ this.seticon(photo); this.setbackground(color.white); } public void flipback(){ this.setbackground(color.cyan); this.seticon(null); } public string getphotopath(){ return photopath; } @override public boolean equals(object o){ return o instanceof tile && ((tile)o).getphotopath().equals(photopath); } @override public int hashcode(){ return photopath.hashcode(); } }
use swing timer instead of thread.sleep(...). understand thread.sleep(...) puts current thread sleep, here swing event dispatch thread or edt, , put entire gui sleep, freezing application. swing timer 1 or repeated actions without tying edt. example:
public void actionperformed(actionevent e) { tile tile = (tile) e.getsource(); if (tilesflipped < 2) { tile.flip(); flippedtiles[tilesflipped++] = tile; if (tilesflipped == 1) { return; } if (flippedtiles[0].equals(flippedtiles[1])) { tilesflipped = 0; return; } else { timer timer = new timer(1000, new actionlistener() { @override public void actionperformed(actionevent e) { (int = 0; < 2; i++) { flippedtiles[i].flipback(); } tilesflipped = 0; } }); timer.setrepeats(false); timer.start(); } } }
Comments
Post a Comment