gpt4 book ai didi

java - glassPane 没有阻止输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:30:33 25 4
gpt4 key购买 nike

我用 java 构建了一个小型 GUI 游戏,有时我使用 glassPane 暂时阻止所有鼠标输入。我以前使用过 glassPane 没有任何问题,但这次它不会阻止鼠标输入。因此,在启用 glassPane 的情况下,我仍然可以按下驻留在 contentPane 上的按钮,我确定它已启用,因为我可以看到我在其上绘制的内容。

这是一小段显示问题的可运行代码:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class GuiGame {

private JPanel contentPane;
private JButton button;
private JFrame frame;
private JPanel glassPane;
private Dimension screenSize;

public static void main(String[] args) {
GuiGame gui = new GuiGame();
gui.createGUI();
}

public void createGUI()
{
frame = new JFrame("BadGuiGame!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(400, 400));
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
frame.setContentPane(contentPane);
frame.pack();

glassPane = new JPanel();
glassPane.setOpaque(false);
glassPane.setLayout(null);
JLabel glassLabel = new JLabel("Glass Enabled");
glassLabel.setBounds(160, 50, 80, 20);
glassPane.add(glassLabel);
frame.setGlassPane(glassPane);

int buttonWidth = frame.getWidth()/2;
int buttonHeight = frame.getHeight()/4;
int xButton = (frame.getWidth() - buttonWidth)/2;
int yButton = frame.getHeight()/2;
button = new JButton("NEXT LEVEL!");
button.setFocusable(false);
button.setEnabled(true);
button.setBounds(xButton, yButton, buttonWidth, buttonHeight);
contentPane.add(button);

int x = (screenSize.width - frame.getWidth())/2;
int y = (screenSize.height - frame.getHeight())/2;
frame.setLocation(x, y);
frame.setVisible(true);
glassPane.setVisible(true);
}
}

最佳答案

我会尝试将 MouseListener 添加到您的玻璃面板,并在所有 MouseEvents 上使用该事件,例如

public void  mouseClicked(MouseEvent e) {
e.consume();
}

关于java - glassPane 没有阻止输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5761472/

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