Chess: java swing help need

Hi, I have just learn java swing and now creating a chess game. I have sucessfully create a board and able to display chess pieces on the board. By using JLayeredPane, I am able to use drag and drop for the piece. However, there is a problem which is that I can drop the chess piece off the board and the piece would disappear. I have try to solve this problem by trying to find the location that the chess piece is on, store it somewhere and check if the chess piece have been drop off bound. However, I could not manage to solve it. Also, I am very confuse with all these layer thing.

Any suggestion would be very helpful. Thanks in advance

import java.awt.*;

import java.awt.event.*;

import java.util.*;

import javax.swing.*;

public class ChessBoard extends JFrame implements MouseListener, MouseMotionListener

{

Object currentPosition;

Color currentColor;

Dimension boardSize = new Dimension(600, 600);

JLayeredPane layeredPane;

JPanel board;

JPanel box;

JLabel chessPiece;

int xAdjustment;

int yAdjustment;

public ChessBoard()

{

// Use a Layered Pane for this this application

layeredPane = new JLayeredPane();

getContentPane().add(layeredPane);

layeredPane.setPreferredSize( boardSize );

layeredPane.addMouseListener( this );

layeredPane.addMouseMotionListener( this );

// Add a chess board to the Layered Pane

board = new JPanel();

// set "board" to the lowest layer (default_layer)

layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);

board.setLayout( new GridLayout(8, 8) );

board.setPreferredSize( boardSize );

board.setBounds(0, 0, boardSize.width, boardSize.height);

addShade();

addPiece();

}

public void addShade()

{

for (int i = 0; i < 64; i++)

{

box = new JPanel( new BorderLayout() );

board.add( box, BorderLayout.CENTER );

if( ((i / 8) % 2) == 0)

{

if( (i % 2) ==0)

{

box.setBackground(Color.lightGray);

} else {

box.setBackground( Color.white);

}

} else {

if( (i % 2) ==0)

{

box.setBackground(Color.white);

} else {

box.setBackground(Color.lightGray);

}

}

}

}

//Method for adding chess pieces to the board

public void addPiece()

{

// Add a few pieces to the board

//black pieces

for (int i = 0; i < 64; i++)

{

//adding black pieces

if (i < 8)

{

String fileName = i + ".gif";

JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( i );

panel.add( blackPieces );

}

//adding black pones

if ((i > 7) && (i < 16))

{

String fileName = "8.gif";

JLabel blackPones = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( i );

panel.add( blackPones );

}

//jump to white position (Component 48)

if (i == 16) i = 48;

//adding white pones

if(( i > 47 ) && (i < 56))

{

JLabel whitePones = new JLabel( new ImageIcon("48.gif") );

JPanel panel = (JPanel)board.getComponent( i );

panel.add( whitePones );

}

//adding white pieces

if (i > 55)

{

String fileName = i + ".gif";

JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( i);

panel.add( whitePieces );

}

}

}

/*

** Add the selected chess piece to the dragging layer so it can be moved

*/

public void mousePressed(MouseEvent e)

{

chessPiece = null;

Component c = board.findComponentAt(e.getX(), e.getY());

c.setBackground(Color.red);

if (c instanceof JPanel) return;

Point parentLocation = c.getParent().getLocation();

xAdjustment = parentLocation.x - e.getX();

yAdjustment = parentLocation.y - e.getY();

chessPiece = (JLabel)c;

chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);

chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());

layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);

}

/*

** Move the chess piece around

*/

public void mouseDragged(MouseEvent me)

{

if (chessPiece == null) return;

chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);

}

/*

** Drop the chess piece back onto the chess board

*/

public void mouseReleased(MouseEvent e)

{

Component c = board.findComponentAt(e.getX(), e.getY());

int x = (int)c.getBounds().getX();

int y = (int)c.getBounds().getY();

System.out.println(c.getLocation());

System.out.println(x + " "+ y);

c.setBackground(currentColor);

if (chessPiece == null) return;

chessPiece.setVisible(false);

if (c instanceof JLabel)

{

Container parent = c.getParent();

//remove the piece that is capture

parent.remove(0);

parent.add( chessPiece );

}

else

{

Container parent = (Container)c;

parent.add( chessPiece );

}

chessPiece.setVisible(true);

}

public void mouseClicked(MouseEvent e) {}

public void mouseMoved(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

private static void createAndShowGUI()

{

//Make sure we have nice window decorations

JFrame.setDefaultLookAndFeelDecorated(true);

JFrame frame = new ChessBoard();

frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );

//Display the window

frame.pack();

frame.setResizable( false );

frame.setLocationRelativeTo( null );

frame.setVisible(true);

}

public static void main(String[] args)

{

//Schedule a job for the event-dispatching thread:

//creating and showing this application's GUI

javax.swing.SwingUtilities.invokeLater( new Runnable()

{

public void run()

{

createAndShowGUI();

}

});

}

}

[6307 byte] By [Dino2526a] at [2007-11-27 10:18:52]
# 1

> I have sucessfully create a board and able to display chess pieces on the board

Actually, you just copied my code from a different posting and made a few changes.

The code you copied was nice and formatted and easy to read. If you want people to help then learn how to use the "Code Formatting Tags" so the code you post is readable.

> However, there is a problem which is that I can drop the chess piece off the board and the piece would disappear.

Well you know the mouse location and the size of the board.

So if the x location is less than 0, you use zero.

Also it the x location is greater than the width of the board then you would use the width of the board. Of course the image still won't show so you would then subtract the width of your image from the with of the board as well.

> Also, I am very confuse with all these layer thing

Read the Swing tutorial on "How to Use Layered Panes":

http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html

camickra at 2007-7-28 16:54:11 > top of Java-index,Desktop,Core GUI APIs...
# 2

import java.awt.*;

import java.awt.event.*;

import java.util.*;

import javax.swing.*;

public class ChessBoardRx extends JFrame implements MouseListener, MouseMotionListener

{

Object currentPosition;

Color currentColor;

Dimension boardSize = new Dimension(600, 600);

JLayeredPane layeredPane;

JPanel board;

JPanel box;

JLabel chessPiece;

int xAdjustment;

int yAdjustment;

Container lastParent;

public ChessBoardRx()

{

// Use a Layered Pane for this this application

layeredPane = new JLayeredPane();

getContentPane().add(layeredPane);

layeredPane.setPreferredSize( boardSize );

layeredPane.addMouseListener( this );

layeredPane.addMouseMotionListener( this );

// Add a chess board to the Layered Pane

board = new JPanel();

// set "board" to the lowest layer (default_layer)

layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);

board.setLayout( new GridLayout(8, 8) );

board.setPreferredSize( boardSize );

board.setBounds(0, 0, boardSize.width, boardSize.height);

addShade();

addPiece();

//populateBoard();

}

public void addShade()

{

for (int i = 0; i < 64; i++)

{

box = new JPanel( new BorderLayout() );

board.add( box, BorderLayout.CENTER );

if( ((i / 8) % 2) == 0)

{

if( (i % 2) ==0)

{

box.setBackground(Color.lightGray);

} else {

box.setBackground( Color.white);

}

} else {

if( (i % 2) ==0)

{

box.setBackground(Color.white);

} else {

box.setBackground(Color.lightGray);

}

}

}

}

//Method for adding chess pieces to the board

public void addPiece()

{

// Add a few pieces to the board

//black pieces

for (int i = 0; i < 64; i++)

{

//adding black pieces

if (i < 8)

{

String fileName = i + ".gif";

JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( i );

panel.add( blackPieces );

}

//adding black pones

if ((i > 7) && (i < 16))

{

String fileName = "8.gif";

JLabel blackPones = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( i );

panel.add( blackPones );

}

//jump to white position (Component 48)

if (i == 16) i = 48;

//adding white pones

if(( i > 47 ) && (i < 56))

{

JLabel whitePones = new JLabel( new ImageIcon("48.gif") );

JPanel panel = (JPanel)board.getComponent( i );

panel.add( whitePones );

}

//adding white pieces

if (i > 55)

{

String fileName = i + ".gif";

JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( i);

panel.add( whitePieces );

}

}

}

private void populateBoard() {

int[][] pos = {

{ 9, 7, 5, 1, 3, 5, 7, 9 },

{ 8, 6, 4, 0, 2, 4, 6, 8 }

};

for(int j = 0; j < 8; j++) {

String fileName = "chessImages/" + pos[0][j] + ".jpg";

JLabel label = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( j );

panel.add( label );

}

for(int j = 8; j < 16; j++) {

String fileName = "chessImages/" + 11 + ".jpg";

JLabel label = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( j );

panel.add( label );

}

for(int j = 56, k = 0; j < 64; j++, k++) {

String fileName = "chessImages/" + pos[1][k] + ".jpg";

JLabel label = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( j );

panel.add( label );

}

for(int j = 48; j < 56; j++) {

String fileName = "chessImages/" + 10 + ".jpg";

JLabel label = new JLabel( new ImageIcon( fileName ) );

JPanel panel = (JPanel)board.getComponent( j );

panel.add( label );

}

}

/*

** Add the selected chess piece to the dragging layer so it can be moved

*/

public void mousePressed(MouseEvent e)

{

chessPiece = null;

Component c = board.findComponentAt(e.getX(), e.getY());

c.setBackground(Color.red);

if (c instanceof JPanel) return;

lastParent = c.getParent();

Point parentLocation = c.getParent().getLocation();

xAdjustment = parentLocation.x - e.getX();

yAdjustment = parentLocation.y - e.getY();

chessPiece = (JLabel)c;

chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);

chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());

layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);

}

/*

** Move the chess piece around

*/

public void mouseDragged(MouseEvent me)

{

if (chessPiece == null) return;

chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);

}

/*

** Drop the chess piece back onto the chess board

*/

public void mouseReleased(MouseEvent e)

{

Component c = board.findComponentAt(e.getX(), e.getY());

if(c == null) {

layeredPane.remove(chessPiece);

lastParent.add(chessPiece);

Rectangle r = lastParent.getBounds();

chessPiece.setLocation(r.x+xAdjustment, r.y+yAdjustment);

lastParent.validate();

lastParent.repaint();

return;

}

int x = (int)c.getBounds().getX();

int y = (int)c.getBounds().getY();

System.out.println(c.getLocation());

System.out.println(x + " "+ y);

c.setBackground(currentColor);

if (chessPiece == null) return;

chessPiece.setVisible(false);

if (c instanceof JLabel)

{

Container parent = c.getParent();

//remove the piece that is capture

parent.remove(0);

parent.add( chessPiece );

}

else

{

Container parent = (Container)c;

parent.add( chessPiece );

}

chessPiece.setVisible(true);

}

public void mouseClicked(MouseEvent e) {}

public void mouseMoved(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

private static void createAndShowGUI()

{

//Make sure we have nice window decorations

JFrame.setDefaultLookAndFeelDecorated(true);

JFrame frame = new ChessBoardRx();

frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );

//Display the window

frame.pack();

frame.setResizable( false );

frame.setLocationRelativeTo( null );

frame.setVisible(true);

}

public static void main(String[] args)

{

//Schedule a job for the event-dispatching thread:

//creating and showing this application's GUI

javax.swing.SwingUtilities.invokeLater( new Runnable()

{

public void run()

{

createAndShowGUI();

}

});

}

}

crwooda at 2007-7-28 16:54:12 > top of Java-index,Desktop,Core GUI APIs...