简体   繁体   English

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

[英]Record the last JButton pressed in a grid of JButtons

Hey guys here's the deal I am trying to create a simple chess game using java. 大家好,我正在尝试使用Java创建简单的国际象棋游戏。 I have my board of an [8][8] array of JButtons. 我的板子上有一个[8] [8]的JButtons数组。 I assign each a new SquareListener which is a class that extends BoardListner which a super class that implements Action Listener. 我给每个人分配一个新的SquareListener,它是扩展BoardListner的类,BoardListner是实现Action Listener的超类。 I want to record whether or not the button that is currently being pressed is equal to the last button that was pressed. 我想记录当前被按下的按钮是否等于最后被按下的按钮。 I am storing the JButton instance that is pressed in the super class and referring to that in the SqaureListener actionPerformed method. 我将存储在超类中按下的JButton实例,并在SqaureListener actionPerformed方法中对其进行引用。 Here is the example of the classes that I created for the buttons. 这是我为按钮创建的类的示例。

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;
}

and here is the super class where I am storing the isSelecting data 这是我存储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;
    }

}

I would expect for each time a button is pressed to have a instance of that button passed into buttonPressed and compared to what's stored in BoardListener, to then have that printed out and then to assign buttonPressed to the super member. 我希望每次按下按钮都会将该按钮的实例传递到buttonPressed中,并与BoardListener中存储的内容进行比较,然后打印出来,然后将buttonPressed分配给超级成员。 Instead I am getting the behavior where if I press a button once it will always return "This is the button you last pressed" even If I had pressed a new one in between. 取而代之的是,如果我按下一个按钮,它将始终返回“这是您上次按下的按钮”,即使我在之间按下了一个新按钮也是如此。 Is there something wrong with the way I'm going about this? 我的处理方式有问题吗? Is there any easier way? 有没有更简单的方法?

here is the additional code where I store the buttons and assign them the action listeners 这是我存储按钮并为其分配动作监听器的其他代码

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
    }
}

We don't need a whole grid of 8 x 8, but maybe a 2 x 2 that can be scaled to 8 x 8 by you. 我们不需要8 x 8的整个网格,但也许您可以将其缩放为8 x 8的2 x 2。

This code compares the last coords of the button clicked. 此代码比较单击的按钮的最后一个坐标。

You might use a single ActionListener for all your buttons... 您可以为所有按钮使用一个ActionListener

For example: 例如:

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;
                    }
                }
            }
        }
    };
}

在此处输入图片说明

Also, you might change your white / black algorithm to something like this: 另外,您可以将白色/黑色算法更改为以下形式:

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]);
    }
}

在此处输入图片说明

Each button has its own listener, and each listener has its own lsstButonPressed field, so that can't work. 每个按钮都有自己的侦听器,每个侦听器都有自己的lsstButonPressed字段,因此无法正常工作。

Use the same listener instance for all buttons, or store the last button pressed in the board (or in another object shared by all the listeners). 对所有按钮使用相同的侦听器实例 ,或将最后按下的按钮存储在面板中(或所有侦听器共享的另一个对象中)。

Also, you don't need super to access the lastButtonPressed. 另外,您不需要super权限即可访问lastButtonPressed。

And this 和这个

JButton lastButtonPressed = new JButton();

creates a new JButton for nothing. 创建一个新的JButton。 Just leave the field to null. 只需将该字段留空即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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