【问题标题】:Making a chess game in Java, I want to move the pieces用Java做一个国际象棋游戏,我想移动棋子
【发布时间】:2015-06-19 18:45:57
【问题描述】:

所以我将图像存储为 JButton 上的 ImageIcon。我希望用户单击他们想要使用的作品的 JButton,然后单击另一个 JButton 将其移动到那里,我该怎么做?

我尝试使用 actionListener 来获取 ImageIcon,但事实证明它非常复杂,尤其是因为我有一个 JButton 图像的二维数组。

ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {

                System.out.println(actionEvent.getActionCommand());

            }
        };

        JButton[][] squares = new JButton[8][8];
        Border emptyBorder = BorderFactory.createEmptyBorder();

        for (int row = 0; row < squares.length; row++) {
            for (int col = 0; col < squares[row].length; col++) {

                JButton tempButton = new JButton();

                tempButton.setBorder(emptyBorder);
                tempButton.setSize(64, 64);


                squares[row][col] = tempButton;
                squares[row][col].addActionListener(actionListener);
                panel.add(squares[row][col]);

                squares[0][0].setIcon(new ImageIcon(BoardGUI.class.getResource("castle.png"), "castle"));



            }
        }

【问题讨论】:

  • 如果您将您所拥有的确切问题包含在内,这可能会对人们有所帮助。

标签: java swing jbutton imageicon chess


【解决方案1】:

试试下面的代码。我不知道在 JButtons 上使用 ImageIcons 的确切代码,但这可以让想法得到传达:

JButton pieceToMoveButton = null;   //variable that persists between actionPerformed calls

public void actionPerformed(ActionEvent actionEvent)
{
    JButton button = (JButton)actionEvent.getSource();

    if (pieceToMoveButton == null)    //if this button press is selecting the piece to move
    {
        //save the button used in piece selection for later use
        pieceToMoveButton = button;
    }
    else        //if this button press is selecting where to move
    {
        //move the image to the new button (the one just pressed)
        button.imageIcon = pieceToMoveButton.imageIcon
        pieceToMoveButton = null;    //makes the next button press a piece selection
    }
}

【讨论】:

    【解决方案2】:

    不确定这是否是您要查找的内容,但这是将 JButton 的位置移动到另一个位置的一种方式: 现在作为一个例子,假设已经有代码声明和初始化了一个 JButton(JButton thatotherbutton = new JButton...等)。可以这样将其移动到某个位置:

    Rectangle rect = thatotherbutton.getBounds();
    xcoordinate = (int)rect.getX();
    ycoordinate = (int)rect.getY();
    chesspiecebutton.setBounds(xcoordinate, ycoordinate, xlengthofbutton, ylengthofbutton);
    

    在单击另一个 JButton 时,使用这些坐标设置 JButton 的新边界(即位置)。

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多