java - getX() & getY() MotionListener -
im searching coordinates x/y chessboard contain cases ! use system.out.println it's not method... need these data method getx() , gety() !
column: a-h row: 1-8
im searching since 3 hours.....
import java.awt.color; import java.awt.container; import java.awt.dimension; import java.awt.eventqueue; import java.awt.gridlayout; import java.awt.event.actionevent; import java.awt.event.mouseadapter; import java.awt.event.mouseevent; import javax.swing.jframe; import javax.swing.jpanel; public class coordboutons extends jframe { coordboutons() { super("gridlayout"); setdefaultcloseoperation(exit_on_close); container contenant = getcontentpane(); contenant.setlayout(new gridlayout(8, 8)); (int = 0; < 8; i++) { (int j = 0; j < 8; j++) { contenant.add(new caseechiquier(i, j)); } } pack(); setvisible(true); } class caseechiquier extends jpanel { private int lin, col; caseechiquier(int i, int j) { lin = i; col = j; setpreferredsize(new dimension(80, 75)); setbackground((i + j) % 2 == 0 ? color.white : color.gray); addmouselistener(new mouseadapter() { /* private color background; @override public void mousepressed(mouseevent e) { background = getbackground(); setbackground(color.red); repaint(); } */ @override public void mousepressed(mouseevent e) { system.out.println((char)('a' + col) + "" + (8 - lin)); } @override public void mouseentered(mouseevent e) { } /* @override public void mousereleased(mouseevent e) { setbackground(background); } */ }); // addactionlistener(new actionlistener() { // public void actionperformed(actionevent evt) { // system.out.println((char) ('a' + col) + "" + (8 - lin)); // // } // }); } } public static void main(string[] args) { eventqueue.invokelater(new runnable() { @override public void run() { jframe.setdefaultlookandfeeldecorated(true); coordboutons coordboutons = new coordboutons(); } }); } }
mouseevent have getx
, gety
methods can use coordinates. use below:
public void mouseclicked(mouseevent e) { int x = e.getx(); }
x
in case contain coordinates user pressed mouse button.
update: i've updated code bit regard comment. here use getsource()
cast caseechiquier
since type of object getsource return. after that, have object user pressed , can perform whatever logic want it
public void mouseclicked(mouseevent e){ caseechiquier current =(caseechiquier)e.getsource(); // object user pressed int lin = current.getlin(); int col= current.getcol(); //do else object current }
also need add getlin
, getcol
method caseechiquier class
Comments
Post a Comment