java - JButton 仅在可见性设置为 True-Java 时有效
问题描述
我基本上正在尝试制作一个简单的跳棋游戏,我需要用户只能看到瓷砖和棋子,而不是按钮。当我将可见性设置为 True 时,程序通过给我一条测试消息“嘿,按下了一个按钮!”来工作。但是,当我将可见性设置为 False(我需要它)时,我不再收到测试消息。我从一般的谷歌搜索中看到的唯一与此相关的论坛问题是使用重绘和重新验证,但这些都不起作用,因此我删除了那两行代码。我通常会有一个很好用的按钮类,但由于我的代码只接受静态而不是正常的,我必须直接在我的主类中实现 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
玻璃窗格是不可见的,但仍会接收鼠标移动和单击事件。在玻璃窗格上添加一个单击侦听器并获取鼠标位置,然后检查该位置是否在您的“隐藏”按钮所在的空间之上。
推荐阅读
- python-3.x - 按大小将大文件拆分为较小的块
- facebook-graph-api - 如何编写 Kafka 连接器以与 Facebook API 集成?
- javascript - cmd.exe 和 start.batch 的问题
- laravel - 显示从 guzzle 请求中获取的 BLOB 文件(图像)
- gradle - TestFX Spock Gradle 项目 Openjdk 11 - 零测试结果
- java - 并行自动化测试和线程安全变量
- c++ - HttpQueryInfo 获取文件大小
- bash - 有没有办法创建一个打印出特定段落的bash脚本,即在空行之间打印一个特定的文本块?
- python - 无法导入 numpy
- powershell - 为什么 Invoke-Webrequest 正确返回外来字符而 cURL 没有?