gpt4 book ai didi

java - JButton 仅在可见性设置为 True-Java 时才起作用

转载 作者:行者123 更新时间:2023-12-02 09:09:16 27 4
gpt4 key购买 nike

我基本上想制作一个简单的西洋跳棋游戏,我需要用户只能看到图 block 和棋子,而不是按钮。当我将可见性设置为 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();
}
}
}
}

最佳答案

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

玻璃 Pane 不可见,但仍接收鼠标移动和单击事件。在玻璃 Pane 上添加点击监听器并获取鼠标位置,然后检查该位置是否位于“隐藏”按钮所在的空间上方。

关于java - JButton 仅在可见性设置为 True-Java 时才起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539567/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com