swing - Making a chess game in Java, I want to move the pieces -
so have images stored imageicon's on jbuttons. want user click on jbutton of piece want use , click on jbutton move there, how this?
i've tried using actionlistener imageicon proving complicated because have 2d array of jbutton images.
actionlistener actionlistener = new actionlistener() { public void actionperformed(actionevent actionevent) { system.out.println(actionevent.getactioncommand()); } }; jbutton[][] squares = new jbutton[8][8]; border emptyborder = borderfactory.createemptyborder(); (int row = 0; row < squares.length; row++) { (int col = 0; col < squares[row].length; col++) { jbutton tempbutton = new jbutton(); tempbutton.setborder(emptyborder); tempbutton.setsize(64, 64); squares[row][col] = tempbutton; squares[row][col].addactionlistener(actionlistener); panel.add(squares[row][col]); squares[0][0].seticon(new imageicon(boardgui.class.getresource("castle.png"), "castle")); } }
try following code. don't know exact code working imageicons on jbuttons, gets ideas across:
jbutton piecetomovebutton = null; //variable persists between actionperformed calls public void actionperformed(actionevent actionevent) { jbutton button = (jbutton)actionevent.getsource(); if (piecetomovebutton == null) //if button press selecting piece move { //save button used in piece selection later use piecetomovebutton = button; } else //if button press selecting move { //move image new button (the 1 pressed) button.imageicon = piecetomovebutton.imageicon piecetomovebutton = null; //makes next button press piece selection } }
Comments
Post a Comment