简体   繁体   中英

chess board in java

This is my code below

import javax.swing.*;
import java.awt.*;

public class board2 {

JFrame frame;
JPanel squares[][] = new JPanel[8][8];

public board2() {
    frame = new JFrame("Simplified Chess");
    frame.setSize(500, 500);
    frame.setLayout(new GridLayout(8, 8));

    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            squares[i][j] = new JPanel();

            if ((i + j) % 2 == 0) {
                squares[i][j].setBackground(Color.black);
            } else {
                squares[i][j].setBackground(Color.white);
            }   
            frame.add(squares[i][j]);
        }
    }

    squares[0][0].add(new JLabel(new ImageIcon("rookgreen.png")));
    squares[0][2].add(new JLabel(new ImageIcon("bishopgreen.png")));
    squares[0][4].add(new JLabel(new ImageIcon("kinggreen.png")));
    squares[0][5].add(new JLabel(new ImageIcon("bishopgreen.png")));
    squares[0][7].add(new JLabel(new ImageIcon("rookgreen.png")));

    squares[7][0].add(new JLabel(new ImageIcon("rookred.png")));
    squares[7][2].add(new JLabel(new ImageIcon("bishopred.png")));
    squares[7][4].add(new JLabel(new ImageIcon("kingred.png")));
    squares[7][5].add(new JLabel(new ImageIcon("bishopred.png")));
    squares[7][7].add(new JLabel(new ImageIcon("rookred.png")));

    for (int i = 0; i < 8; i++) {
        squares[1][i].add(new JLabel(new ImageIcon("pawngreen.png")));
        squares[6][i].add(new JLabel(new ImageIcon("pawnred.png")));
    }

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

public static void main(String[] args) {
    new board2();
}
}

I am trying to create a chess game sort of and I need help with putting labels on all sides of the board to label the rows and columns in either AH or 1-8. I have no idea how to do it. Also later on I'll be adding a feature to drag and drop the pieces. Is it best to use JLabels? Anyways I would I go about putting the labels on the side? Thanks!

I would like submitting a simple chess board drawing example using Unicode characters. There 3 classes involved into this tiny project.

ChessLabel.java

import java.awt.Color;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.SwingConstants;


public class ChessLabel extends JLabel {

    Font font     = new Font("Ariel", Font.PLAIN, 24);
    Color bgLight = new Color(222, 184, 135);
    Color bgDark  = new Color(139, 69, 19);

    ChessLabel(String s)
    {
        super(s);
    }

    void set(int idx, int row)
    {
      setFont(font);
          setOpaque(true);
          setBackground((idx+row)%2 == 0 ? bgDark : bgLight);
          setHorizontalAlignment( SwingConstants.CENTER );
    }

}

Board.java

import java.awt.*;
import javax.swing.JFrame;


public class Board extends JFrame {


   //Initialise arrays to hold panels and images of the board

    private ChessLabel[] labels = new ChessLabel[] {

    // white
    new ChessLabel("\u2656"), new ChessLabel("\u2658"), new ChessLabel("\u2657"), 
    new ChessLabel("\u2655"), new ChessLabel("\u2654"), new ChessLabel("\u2657"), 
    new ChessLabel("\u2658"), new ChessLabel("\u2656"), new ChessLabel("\u2659"), 
    new ChessLabel("\u2659"), new ChessLabel("\u2659"), new ChessLabel("\u2659"),
    new ChessLabel("\u2659"), new ChessLabel("\u2659"), new ChessLabel("\u2659"), 
    new  ChessLabel("\u2659"), 
    // empty
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "),
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "), new ChessLabel(" "), 
    new ChessLabel(" "), new ChessLabel(" "),
    // black
    new ChessLabel("\u265F"), new ChessLabel("\u265F"), new ChessLabel("\u265F"), 
    new ChessLabel("\u265F"), new ChessLabel("\u265F"), new ChessLabel("\u265F"), 
    new ChessLabel("\u265F"), new ChessLabel("\u265F"), new ChessLabel("\u265C"), 
    new ChessLabel("\u265E"), new ChessLabel("\u265D"), new ChessLabel("\u265B"), 
    new ChessLabel("\u265A"), new ChessLabel("\u265D"), new ChessLabel("\u265E"), 
    new ChessLabel("\u265C")
    };

    public Board() 
    {

    } // Board()

    void display()
    {
        setTitle("Chess board with unicode images");

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        Container contentPane = getContentPane();
        GridLayout gridLayout = new GridLayout(8, 8);

        contentPane.setLayout(gridLayout);

        int row = -1;
        for (int i = 0; i < labels.length; i++) 
        {
            if(i % 8 == 0) row ++; // increment row number
            labels[i].set(i, row);
            contentPane.add(labels[i]);
        } // i

        setSize(600, 600);
        setLocationRelativeTo(null);
        setVisible(true);
     } // display()

} // class Board

And ChessBoardTest.java

public class ChessBoardTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        Board board = new Board();

        board.display();
    }

}

Go here . This shows some of the different layouts you can use. One thing you may want to look into is the grid layout. This would make it easy for you to add JPanels for the squares. You could also use it to add labels around the board, but that is just one way of doing it. Go through the examples on the site, there is example code too.

public class Pieces {

}

class Pawn_1 extends JComponent {

        private BufferedImage img;
        private Point imgPoint = new Point(0, 65);

        public Pawn_1() {
            try {
                img = ImageIO.read(new File("C:\\imgs\\b_pawn.png"));

            } catch (IOException ex) {
                ex.printStackTrace();
            }

            MouseAdapter ma = new MouseAdapter() {

                private Point offset;

                @Override
                public void mousePressed(MouseEvent e) {
                    Rectangle bounds = getImageBounds();
                    Point mp = e.getPoint();
                    if (bounds.contains(mp)) {
                        offset = new Point();
                        offset.x = mp.x - bounds.x;
                        offset.y = mp.y - bounds.y;
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    offset = null;
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    if (offset != null) {
                        Point mp = e.getPoint();
                        imgPoint.x = mp.x - offset.x;
                        imgPoint.y = mp.y - offset.y;
                        repaint();
                    }
                }

            };
            addMouseListener(ma);
            addMouseMotionListener(ma);
        }

        protected Rectangle getImageBounds() {
            Rectangle bounds = new Rectangle(0, 0, 0, 0);
            if (img != null) {
                bounds.setLocation(imgPoint);
                bounds.setSize(img.getWidth(), img.getHeight());
            }
            return bounds;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(65, 65);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.drawImage(img, imgPoint.x, imgPoint.y, this);
                g2d.dispose();
            }
        }
    }
 public void paintComponent(Graphics g) {                
    Graphics2D g2 = (Graphics2D)g;
    g2.setColor(Color.WHITE);
    int row = 0; 
    int col = 0;
    int sq = 65;

    while(row != (sq * 8)){
        if(row % 10 != 0 && col % 10 == 0)g2.setColor(Color.BLACK);
        if(row % 10 != 0 && col % 10 != 0)g2.setColor(Color.WHITE);
        if(row % 10 == 0 && col % 10 == 0)g2.setColor(Color.WHITE);
        if(row % 10 == 0 && col % 10 != 0)g2.setColor(Color.BLACK);

        g2.fillRect(row, col, sq, sq);
        row = row + sq;
        if(row == (sq * 8)){
            row = 0;
            col = col + sq;
            if(col == (sq * 8))break;
        }
    }


}
import java.awt.*;
import java.applet.*;
public class MyChes extends Applet
{
    public void paint(Graphics g)
    {
        for(int i=50;i<=400;i+=50)
        {
           for(int j=50;j<=400;j+=50)
           {
               if((i+j)%100==0)
               {
                  g.setColor(Color.black);
                  g.fillRect(i,j,50,50);
               }
           }
           g.drawRect(50,50,400,400);
         }
     }
}

import java.applet.*;
import java.lang.*;
import java.awt.*;

public class E10_2 extends Applet
{
    public void paint(Graphics g)
    {
        for(int x = 10; x < 330; x+=80)
        {
            for(int y = 10; y < 330; y+=80)
            {
                g.drawRect(8,8,322,322);
                g.drawRect(9,9,322,322);
                g.fillRect(x,y,40,40);
                g.fillRect(x+40,y+40,40,40);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM