Делаю шахматную партию на Java, хочу двигать фигуры

Итак, мои изображения хранятся как ImageIcon на JButtons. Я хочу, чтобы пользователь щелкнул 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"));



            }
        }

person TheRapture87    schedule 19.06.2015    source источник
comment
Вероятно, людям было бы полезно, если бы вы указали, что именно не так с тем, что у вас есть.   -  person Galax    schedule 19.06.2015


Ответы (2)


Попробуйте следующий код. Я не знаю точного кода для работы с ImageIcons на JButtons, но это передает идеи:

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
    }
}
person Adam Evans    schedule 19.06.2015

Не уверен, что это то, что вы ищете, но это один из способов перемещения позиции 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.

person Magerick    schedule 20.06.2015