记录在JButtons网格中按下的最后一个JButton

时间:2017-03-03 23:03:44

标签: java swing

嘿伙计们这里是我正在尝试使用java创建一个简单的国际象棋游戏。我有一个[8] [8] JButton数组的板。我为每个分配了一个新的SquareListener,它是一个扩展BoardListner的类,它是一个实现Action Listener的超类。我想记录当前正在按下的按钮是否等于按下的最后一个按钮。我正在存储在超类中按下的JButton实例,并在SqaureListener actionPerformed方法中引用它。以下是我为按钮创建的类的示例。

public class SquareListener extends BoardListener {
private int row;
private int column;


public SquareListener(int row, int column){
    this.setRow(row);
    this.setColumn(column);
}

@Override
public void actionPerformed(ActionEvent ae){
    JButton buttonPressed = (JButton) ae.getSource();
    if(buttonPressed == super.lastButtonPressed){
        System.out.println("This is the button you last pressed");
    }else{
        System.out.println("This is a new button");
    }
    super.lastButtonPressed = buttonPressed;
}

这里是我存储isSelecting数据的超类

public class BoardListener implements ActionListener {

    private boolean isSelectingInsteadOfTargeting = true;
    JButton lastButtonPressed = new JButton();

    @Override
     public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    }

    public boolean isSelectingInsteadOfTargeting() {
        return isSelectingInsteadOfTargeting;
    }

    public void setSelectingInsteadOfTargeting(boolean isSelectingInsteadOfTargeting) {
    this.isSelectingInsteadOfTargeting = isSelectingInsteadOfTargeting;
    }

}

我希望每次按下一个按钮,将该按钮的实例传递给buttonPressed并与BoardListener中存储的内容进行比较,然后将其打印出来,然后将buttonPressed分配给超级成员。相反,我得到的行为如果我按下一个按钮,它将始终返回“这是你上次按下的按钮”,即使我在中间按了一个新按钮。我这样做的方式有问题吗?有没有更简单的方法?

这是我存储按钮并为其分配动作侦听器的附加代码

public Board(boolean _isWhite){
    gui = new JPanel(new GridLayout(8,8));
    chessBoardSquares = new Square[8][8];
    boolean shouldBeWhite = true;
    for(int i = 0; i < 8; i++){
        for(int j= 0; j < 8; j++){
            Square square = new Square(i,j);
            square.getButton().addActionListener(new SquareListener(i,j));
            if(shouldBeWhite){
                square.getButton().setBackground(Color.WHITE);
                shouldBeWhite = false;
            }else{
                square.getButton().setBackground(Color.BLACK);
                shouldBeWhite = true;
            }
            if (j == 7){
                shouldBeWhite = !shouldBeWhite;
            }
            chessBoardSquares[i][j] = square;
            gui.add(chessBoardSquares[i][j].getButton());
        }
    }
    BoardFactory boardFactory = new BoardFactory();
    if(_isWhite){
        updateBoardIconsBasedOnCurrentBoardArray(boardFactory.getBlackStartArray());
    }else{
        //getblack start array and invoke method to change button icons based on array
    }
}

2 个答案:

答案 0 :(得分:4)

我们不需要8 x 8的整个网格,但可能是2 x 2,可以由你缩放到8 x 8。

此代码比较单击按钮的最后一个坐标。

您可以为所有按钮使用一个ActionListener ...

例如:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TwiceButtonPressed {

    private JFrame frame;

    private JButton[][] buttons;

    private JLabel label;
    private JLabel sameButtonLabel;

    private JPanel pane;

    private boolean sameButtonPressed;

    private static final int rows = 2;
    private static final int cols = 2;

    private int buttonRow = -1;
    private int buttonCol = -1;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new TwiceButtonPressed().createAndShowGui()); 
    }

    public void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());

        sameButtonPressed = false;

        label = new JLabel("Button pressed: NONE");
        sameButtonLabel = new JLabel("Same button pressed: " + sameButtonPressed);

        pane = new JPanel();
        pane.setLayout(new GridLayout(rows, cols));

        buttons = new JButton[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                buttons[i][j] = new JButton(i + "" + j);
                buttons[i][j].addActionListener(listener);
                pane.add(buttons[i][j]);
            }
        }

        frame.add(sameButtonLabel, BorderLayout.NORTH);
        frame.add(pane, BorderLayout.CENTER);
        frame.add(label, BorderLayout.SOUTH);

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

    public ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    if (e.getSource().equals(buttons[i][j])) {
                        label.setText("Button pressed: " + buttons[i][j].getText());
                        System.out.println(buttonRow + "==" + i + "***" + buttonCol + "==" + j);
                        if (buttonRow == i && buttonCol == j) {
                            sameButtonPressed = true;
                        } else {
                            sameButtonPressed = false;
                        }
                        sameButtonLabel.setText("Same button pressed: " + sameButtonPressed);
                        buttonRow = i;
                        buttonCol = j;
                    }
                }
            }
        }
    };
}

enter image description here

此外,您可以将白/黑算法更改为以下内容:

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        buttons[i][j] = new JButton() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(50, 50);
            }
        };
        buttons[i][j].addActionListener(listener);
        if (i % 2 == 0) {
            if (j % 2 == 0) {
                buttons[i][j].setBackground(Color.BLACK);
            } else {
                buttons[i][j].setBackground(Color.WHITE);
            }
        } else {
            if (j % 2 != 0) {
                buttons[i][j].setBackground(Color.BLACK);
            } else {
                buttons[i][j].setBackground(Color.WHITE);
            }
        }
        pane.add(buttons[i][j]);
    }
}

enter image description here

答案 1 :(得分:3)

每个按钮都有自己的监听器,每个监听器都有自己的lsstButonPressed字段,因此无法工作。

对所有按钮使用相同的侦听器实例,或者存储在棋盘中按下的最后一个按钮(或所有侦听器共享的另一个对象)。

另外,您不需要super来访问lastButtonPressed。

这个

JButton lastButtonPressed = new JButton();

无需创建新的JButton。只需将该字段留空即可。