如何使用GridLayout中的特定元素?

时间:2013-01-31 08:59:53

标签: java swing jframe layout-manager grid-layout

我在gridlayout中向特定元素(网格?)添加图标时遇到问题。我的gridlayout包含64个“砖块”,用作棋盘。

我的网格代码如下:

器ChessBoard

public class SjakkBrett extends JFrame implements Config {

public ChessBoard() {

    setSize(800,800);
    setLayout(new GridLayout(BRICKS/ ROWS, 0) );

    for (int id = 0; id < BRICKS; id++)         
        add(new Brick(id)); 

    setVisible(true);

}

配置

public interface Config {
    public int ROWS= 8;
    public int BRICKS= 64;
}

我的问题是我似乎无法找到一种方法来将图标添加到电路板中的特定砖块,例如setIcon(new ImageIcon("pawn.png"));,因为我不知道如何使用我正在制作的砖ID

任何可以帮助我的人?

4 个答案:

答案 0 :(得分:4)

回答您的具体问题:

List<Brick> bricks = new ArrayList<Brick>();

public ChessBoard() {

    setSize(800,800);
    setLayout(new GridLayout(BRICKS/ ROWS, 0) );

    for (int id = 0; id < BRICKS; id++) {
        Brick brick = new Brick(id);        
        add(brick); 
        bricks.add(brick);
    }

    setVisible(true);

}

public void setBrick(int id, int piece) {
    bricks.get(id).setPiece(piece);
}

要回答你未提出的问题,让我们考虑一下象棋游戏。

enter image description here

国际象棋棋盘已经有了一个符号。典型的第一步是e4。由于未指定一块,这意味着一个棋子。可以移动到e4的唯一棋子是坐在e2上的棋子。因此,e4是说“将棋子从e2移动到e4”的简写方式。

所以,我们有砖(正方形)被安排成一块板。根据每件作品的不同规则,我们可以从一块砖移动到另一块砖。我们还有用于确定谁获胜的捕获规则和规则。

所有这些元素必须作为对象或方法存在于游戏中。

所以,让我们谈谈对象。

我们有一块砖(方形)。 我们有一组称为板的砖块。 我们有件。

这些对象是相互关联的。它们的共同点是位置的概念。

砖块位于特定位置(e2)。 董事会需要知道如何将一个点(e2)转换成有意义的东西(第1行,第4列;假设第0行,第0列是左下角)。 一件作品需要知道它所在的位置(e2),它可以合法地去哪里(e3,e4),以及它将去哪里(e4)。

这应该足以让你入门。

答案 1 :(得分:3)

  

使用图标添加标签可能会让它更容易一些   我猜想以后可以制作可移动的棋子,但我还是不知道   如何将标签添加到gridlayout中的特定ID。砖是   只是从Config获取它的信息,它被声明(?)   如果我在这里使用了错误的名字和内容,我很抱歉   使用java实际使用它。

  • 查看put/getClientProperty,然后来自KeyboardMouseXxxListener的任何操作/事件都会返回JLabelJButtons数组中的正确坐标}

  • 您可以使用多个put/getClientProperty,但没有任何限制

  • 我将使用JButtonimplemented setXxxIcon in API)代替JLabelrepaint()需要MouseMotionListener的调用)

答案 2 :(得分:2)

我已经把这个代码放在我自己的国际象棋游戏的基础上。

基本上由6个班组成:

  • Test基本上持有main并创建GUI以及将一个棋子加载到棋盘上。
  • NotationPanel用于在棋盘一侧显示行和颜色。
  • Chessboard包含构成电路板的所有ChessboardBlock,也会在适当的位置放置带有黑白标签的电路板。
  • ChessboardBlock具有设定的位置(即A4等)并且可以容纳ChessPiece个实例。
  • ChessPiece,其中包含Piece个实例的数据/图片。
  • ChessPieceMouseAdapter来处理Piece s的拖放:

enter image description here

典型行动的输出:

  

从位置:A1件类型:骑士件颜色:白色

     

到位置:D3件类型:骑士件颜色:白色

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;

public class Test {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                ChessPieceMouseAdapter chessPieceMouseAdapter = new ChessPieceMouseAdapter() {
                    @Override
                    boolean chessPieceSelected(ChessPiece chessPiece, ChessboardBlock cb) {
                        System.out.println("From Location: " + chessPiece.getLocation()
                                + " Piece Type: " + chessPiece.getType()
                                + " Piece Color: " + chessPiece.getColor());
                        return true;
                    }

                    @Override
                    void chessPiecePlaced(ChessPiece chessPiece, ChessboardBlock cb) {
                        cb.setPiece(new ChessPiece(chessPiece.getImage(),
                                chessPiece.getType(),
                                cb.getBlockLocation(),
                                chessPiece.getColor()));

                        System.out.println("To Location: " + cb.getChessPiece().getLocation()
                                + " Piece Type: " + cb.getChessPiece().getType()
                                + " Piece Color: " + cb.getChessPiece().getColor());
                    }
                };

                Chessboard chessBoard = new Chessboard(chessPieceMouseAdapter);
                chessPieceMouseAdapter.setChessboard(chessBoard);//or else NPE will be thrown when press/drag/release on chessboard occurs

                BufferedImage knightImage = null;
                try {
                    knightImage = ImageIO.read(new URL("http://i.stack.imgur.com/qdppY.png"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ChessPiece knightPiece = new ChessPiece(knightImage, "Knight", null, "White");//location parameter can be null or anything will be set if matching block is found
                chessBoard.setChessPiece("A1", knightPiece);

                NotationPanel rows = new NotationPanel(new String[]{"8", "7", "6", "5", "4", "3", "2", "1"}, NotationPanel.VERTICAL);
                NotationPanel cols = new NotationPanel(new String[]{"A", "B", "C", "D", "E", "F", "G", "H"}, NotationPanel.HORIZONTAL);

                frame.add(rows, BorderLayout.WEST);
                frame.add(cols, BorderLayout.SOUTH);
                frame.add(chessBoard);

                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

class NotationPanel extends JPanel {

    final static String HORIZONTAL = "horizontal";
    final static String VERTICAL = "vertical";

    public NotationPanel(String[] strings, String direction) {
        if (direction.equals(VERTICAL)) {
            setLayout(new GridLayout(8, 0));
        } else {
            setLayout(new GridLayout(0, 8));
        }
        for (String string : strings) {
            this.add(new JLabel(string, JLabel.CENTER));
        }

    }
}

class Chessboard extends JPanel {

    private final ArrayList<ChessboardBlock> chessBoardBlocks;
    ChessPieceMouseAdapter chessPieceMouseAdapter;

    public Chessboard(ChessPieceMouseAdapter chessPieceMouseAdapter) {
        super(new GridLayout(8, 8));
        chessBoardBlocks = new ArrayList<>(64);
        layoutBoard();
        this.chessPieceMouseAdapter = chessPieceMouseAdapter;
        addMouseListener(this.chessPieceMouseAdapter);
        addMouseMotionListener(this.chessPieceMouseAdapter);
    }

    private void layoutBoard() {
        String[] cols = new String[]{"A", "B", "C", "D", "E", "F", "G", "H"};
        int[] rows = new int[]{1, 2, 3, 4, 5, 6, 7, 8};
        int NUMBER_OF_BLOCKS = 64;
        String row, col;
        int rowCount = 7, colCount = 0, trigger = 8;

        for (int i = 0; i < NUMBER_OF_BLOCKS; i++) {
            if (trigger == 0) {
                colCount = 0;
                trigger = 8;
                rowCount--;
            }
            col = cols[colCount++];
            row = String.valueOf(rows[rowCount]);
            trigger--;

            Color pieceHolderColor = ((rowCount + colCount) % 2 == 0 ? Color.WHITE : Color.BLACK);
            String pieceHolderLocation = col + row;

            ChessboardBlock pieceHolder = new ChessboardBlock(pieceHolderLocation, pieceHolderColor);
            pieceHolder.setPiece(null);

            add(pieceHolder);//add to the board
            chessBoardBlocks.add(pieceHolder);//add to piece holder array
        }
    }

    boolean setChessPiece(String location, ChessPiece piece) {
        for (int i = 0; i < chessBoardBlocks.size(); i++) {
            if (chessBoardBlocks.get(i).getBlockLocation().equalsIgnoreCase(location)) {
                chessBoardBlocks.get(i).setPiece(new ChessPiece(piece.getImage(),
                        piece.getType(), chessBoardBlocks.get(i).getBlockLocation(),
                        piece.getColor()));
                return true;
            }
        }
        return false;
    }

    public ArrayList<ChessboardBlock> getChessBoardBlocks() {
        return chessBoardBlocks;
    }

    @Override
    protected void paintChildren(Graphics g) {
        super.paintChildren(g);

        if (chessPieceMouseAdapter.isDragging()) {
            if (chessPieceMouseAdapter.getDraggedPiece() != null) {
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

                g2d.drawImage(chessPieceMouseAdapter.getDraggedPiece().getImage(),
                        chessPieceMouseAdapter.getDraggedPieceLocation().x, chessPieceMouseAdapter.getDraggedPieceLocation().y, this);
            }
        }
    }
}

class ChessboardBlock extends JLabel {

    private final Dimension labelDimensions = new Dimension(50, 50);
    private ChessPiece chessPiece;
    private String location;

    public ChessboardBlock(String location, Color backgroundColor) {
        //super(location,JLabel.CENTER);//puts location as text on label
        this.location = location;
        setBackground(backgroundColor);
        setOpaque(true);
    }

    @Override
    public Dimension getPreferredSize() {
        return labelDimensions;
    }

    void setPiece(ChessPiece p) {
        this.chessPiece = p;
        if (chessPiece == null) {
            setIcon(null);
        } else if (chessPiece.getImage() != null) {
            setIcon(new ImageIcon(chessPiece.getImage()));
        }
    }

    String getBlockLocation() {
        return location;
    }

    public ChessPiece getChessPiece() {
        return chessPiece;
    }
}

class ChessPiece {

    private BufferedImage image;
    private String location;
    private String type;
    private final String color;

    public ChessPiece(BufferedImage image, String type, String location, String color) {
        this.image = image;
        this.type = type;
        this.location = location;
        this.color = color;
    }

    public ChessPiece(ChessPiece p) {
        this.image = p.getImage();
        this.type = p.getType();
        this.location = p.getLocation();
        this.color = p.getColor();
    }

    public String getLocation() {
        return location;
    }

    public String getColor() {
        return color;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public BufferedImage getImage() {
        return image;
    }

    String getType() {
        return type;
    }
}

abstract class ChessPieceMouseAdapter extends MouseAdapter {

    private Chessboard chessboard;
    private ChessPiece draggedChessPiece;
    private boolean dragging;
    private Rectangle pieceRectangle;
    private Point draggedPieceInitialLocation;
    private Point pressedPoint;

    public ChessPieceMouseAdapter() {
        dragging = false;
        draggedPieceInitialLocation = new Point();
        pressedPoint = new Point();
    }

    public Point getDraggedPieceLocation() {
        return new Point(pieceRectangle.x, pieceRectangle.y);
    }

    public ChessPiece getDraggedPiece() {
        return draggedChessPiece;
    }

    @Override
    public void mousePressed(MouseEvent me) {
        pressedPoint = me.getPoint();
        ArrayList<ChessboardBlock> chessBoardBlocks = chessboard.getChessBoardBlocks();
        for (int i = 0; i < chessBoardBlocks.size(); i++) {
            if (chessBoardBlocks.get(i).getChessPiece() != null) {
                pieceRectangle = chessBoardBlocks.get(i).getBounds();
                if (pieceRectangle.contains(pressedPoint)) {
                    ChessPiece chessPiece = chessBoardBlocks.get(i).getChessPiece();
                    if (chessPieceSelected(chessPiece, chessBoardBlocks.get(i))) {
                        draggedChessPiece = new ChessPiece(chessPiece);
                        chessBoardBlocks.get(i).setPiece(null);

                        draggedPieceInitialLocation.x = pieceRectangle.x;
                        draggedPieceInitialLocation.y = pieceRectangle.y;

                        dragging = true;
                        chessboard.repaint();
                    }
                    break;
                }
            }
        }
    }

    @Override
    public void mouseReleased(MouseEvent me) {

        ArrayList<ChessboardBlock> chessBoardBlocks = chessboard.getChessBoardBlocks();
        for (int i = 0; i < chessBoardBlocks.size(); i++) {
            pieceRectangle = chessBoardBlocks.get(i).getBounds();
            if (pieceRectangle.contains(me.getPoint())) {
                if (draggedChessPiece != null) {
                    chessPiecePlaced(draggedChessPiece, chessBoardBlocks.get(i));
                }
            }
        }
        dragging = false;
        draggedChessPiece = null;
        chessboard.repaint();
    }

    @Override
    public void mouseDragged(MouseEvent me) {
        dragging = true;
        pieceRectangle.x = me.getX() - (pressedPoint.x - draggedPieceInitialLocation.x);
        pieceRectangle.y = me.getY() - (pressedPoint.y - draggedPieceInitialLocation.y);
        chessboard.repaint();
    }

    boolean isDragging() {
        return dragging;
    }

    abstract boolean chessPieceSelected(ChessPiece chessPiece, ChessboardBlock cb);

    abstract void chessPiecePlaced(ChessPiece chessPiece, ChessboardBlock cb);

    void setChessboard(Chessboard chessBoard) {
        this.chessboard = chessBoard;
    }
}

答案 3 :(得分:0)

首先,您有new GridLayout(BRICKS/ ROWS, 0),表示您将布局设置为0列。 (API指定GridLayout(int rows, int cols)

至于找到x, y coords的问题,你不需要。如果您有占位符(即自定义标签),则可以将背景颜色设置为与纸板单元格对应,并将图像保留在单元格中。可以将图像设置在背景之上,以便为国际象棋的外观和感觉。 点击标签上的事件,以便当用户点击标签时,无论你需要它做什么(将一个单元移动到另一个单元格或从一个单元格移动到另一个单元格,玩家拿一块,检查棋盘上的配合/检查配合等等) 。)

您可以在标签上实施MouseListener的{​​{1}}和mousePressed方法来获取所需的开始和结束标签,如果您想要拖放功能,可以实现{{1董事会的mouseReleased方法和自定义MouseMotionListener方法(不是标签)。