I have an array of JButton
s which are displayed on a window when it is loaded up.
For some reason, when the window loads, the first button seems to be already selected and so puts my programme into an infinite loop.
I know that to stop this infinite loop I should change the condition in my while(true)
loop, but am unsure what conditions to put in.
So I thought another way round would be to figure out why one of the buttons is already selected.
actionPerformed
method - this gets the name of the button selected which I made to be a string to represent co-ordinates. It then turns the co-ordinates into integers which can be obtained by the HumanPlayer class with the getXInt and getYInt methods. The board and pieces are already set up in other classes, I know it all works because i've already created a text version, this is now the GUI version I am working on.
It's just a case of enabling the user to select a button without the while(true) loop getting stuck.
The Screen class:
public void actionPerformed(ActionEvent e) {
JButton piece = (JButton) e.getSource();
String xy = piece.getName();
String x = xy.substring(0,1);
String y = xy.substring(2,3);
xInt = Integer.parseInt(x);
yInt = Integer.parseInt(y);
}
public int getXInt() {
return xInt;
}
public int getYInt() {
return yInt;
}
HumanPlayer class which gets the information of the piece selected and checks whether it can be moved.
//Sets up new instance of Screen class which is where the window displaying the buttons is set up (this contains the getXInt and getYInt methods are- so the HumanPlayer class can retrieve the piece which has been selected.
Screen s = new Screen(board);
public boolean makeMove() {
int fromXCo , fromYCo, toXCo, toYCo;
Piece p;
ArrayList<Move> moves = null;
while (true){
//reads x and y co-ordinate
System.out.println("Click on a piece to move");
//takes information from which button is clicked from other class
fromXCo = s.getXInt();
fromYCo = s.getYInt();
p = board.getPiece(fromXCo, fromYCo);
System.out.println("Your selected piece is " + p.getChar());
//looks through available moves for piece
moves = p.availableMoves();
//if no moves available, asks for new co-ordinates.
if (moves == null)
{
System.out.println("No moves available for this piece \n");
continue;
}
break;
}
So the output is a continuous:
- Click on a piece to move
- Your selected piece is r
- There are no available moves for this piece...