Hello, I'm new to this site, and i really need help with something. I have been working on a checkerboard project for my second programming class, and now I'm stuck. I now how to set the icons, but now I am absolutely confounded as to how I move the icon from one jbutton to the nu=ext as a way of movement. I want to be able to do this by use of a set of mouse clicks. I also need to figure out how to do the AI for the opponent. Someone told me that i should set up a separate class for the pieces. I really need help, and this is only my first year doing programming. Any help would be appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
public class CheckerBoard extends JFrame
{
Scanner scan = new Scanner(System.in);
public static final int SIDE = 8;
private Container contents;
private JButton [][] squares;
Icon redPiece = new ImageIcon("RedPiece.png");
Icon blackPiece = new ImageIcon("BlackPiece.png");
Icon kingPiece = new ImageIcon("Ring.png");
public CheckerBoard( )
{
super( "Click a square to reveal its position" );
contents = getContentPane( );
// set layout to an 8-by-8 Grid
contents.setLayout( new GridLayout( SIDE, SIDE ) );
squares = new JButton[SIDE][SIDE];
ButtonHandler bh = new ButtonHandler( );
for ( int i = 0; i < SIDE; i++ )
{
for ( int j = 0; j < SIDE; j++ )
{
// instantiate JButton array
squares[i][j] = new JButton( );
// make every other square red
if ( ( i + j ) % 2 == 0 )
squares[i][j].setBackground( Color.RED );
if ( ( i + j ) % 2 != 0 )
squares[i][j].setBackground( Color.BLACK );
if(squares[i][j].getBackground()==Color.black && i>=5)
squares[i][j].setIcon(blackPiece);
if(squares[i][j].getBackground()==Color.black && i<3)
squares[i][j].setIcon(redPiece);
// add the JButton
contents.add( squares[i][j] );
// register listener on button
squares[i][j].addActionListener( bh );
}
}
setSize( 400, 400 );
setVisible( true );
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent ae )
{
for ( int i = 0; i < SIDE; i++ )
{
for ( int j = 0; j < SIDE; j++ )
{
if(ae.getSource() == squares[i][j] && squares[i][j].getIcon() == blackPiece)
{
squares[i][j].setIcon(null);
}
else if(ae.getSource() == squares[i][j] && squares[i][j].getIcon() == null && squares[i][j].getBackground() != Color.red)
{
squares[i][j].setIcon(blackPiece);
}
else if(ae.getSource() == squares[i][j] && squares[i][j].getIcon() == redPiece && squares[i][j].getBackground() != Color.red && i==0)
{
squares[i][j].setIcon(kingPiece);
}
}
}
}
}
public static void main( String [] args )
{
CheckerBoard myGame = new CheckerBoard( );
myGame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}