JButton 仅在 Visibility 设置为 True 时有效-Java

JButton Only Works When Visibility is Set to True-Java

我主要是想做一个简单的西洋跳棋游戏,我需要用户只能看到棋子和棋子,而不是按钮。当我将可见性设置为 True 时,程序通过给我一条 "Hey a button was pressed!" 的测试消息来工作。但是,当我将可见性设置为 False(我需要的)时,我不再收到测试消息。我从一般 google 搜索中看到的唯一与此相关的论坛问题是使用重绘和重新验证,但它们不起作用,因此我删除了这两行代码。我通常会有一个很好用的按钮 class,但由于我的代码只接受静态而不是正常,我必须直接在我的主 class 中实现 jbutton。那么到底出了什么问题呢?这是我的代码,在此先感谢。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import java.util.*;

@SuppressWarnings("serial")
public class CheckersMain extends JButton implements ActionListener {

    private static JFrame window;
    private static Color winBackground=Color.GRAY;
    private static Color tile1Color=Color.WHITE;
    private static Color tile2Color=Color.BLACK;
    private static int windowWidth=1000;
    private static int windowHeight=1000;
    private static int setScreenLoc=500;
    private static int tileDimention=100;
    private static Board board;
    private static ArrayList<JButton> allButtons=new ArrayList<JButton>();
    private static ArrayList<Tile> allTiles;

    public static void main(String[] args) {
        window=new JFrame();
        window.setLayout(null);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setTitle("Checkers");
        window.setLocation(setScreenLoc,setScreenLoc);
        window.setSize(windowWidth,windowHeight);
        window.setResizable(false);
        window.getContentPane().setBackground(winBackground);
        window.setVisible(true);
        board=new Board(window,tileDimention,tile1Color,tile2Color);
        allTiles=board.setUp();
        setUpButtons();
        window.repaint();
    }

    private static void setUpButtons() {
        for (int i=0;i<allTiles.size();++i) {
            Tile currentTile=allTiles.get(i);
            JButton button=new JButton();
            button.setSize(tileDimention,tileDimention);
            button.setLocation(currentTile.getXlocation(),currentTile.getYlocation());
            window.add(button,0);
            button.addActionListener(new CheckersMain());
            button.setVisible(false);
            allButtons.add(button);
        }
    }

    private void buttonPressed() {
        System.out.println("Hey a button was pressed!");
    }
    public void actionPerformed(ActionEvent frame) {
        for (int i=0;i<allButtons.size();++i) {
            if (frame.getSource()==allButtons.get(i)) {
                buttonPressed();
            }
        }
    }
}

这听起来是使用 Glass Pane 的好地方: https://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html

玻璃面板是不可见的,但仍然接收鼠标移动和点击事件。在玻璃面板上添加一个点击侦听器并获取鼠标位置,然后检查该位置是否在 space 上方,您的 'hidden' 按钮所在的位置。