glassPane没有阻止输入 [英] glassPane is not blocking input

查看:85
本文介绍了glassPane没有阻止输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用Java构建了一个小型GUI游戏,在某些时候,我正在使用glassPane暂时阻止所有鼠标输入.我以前使用过glassPane都没有任何问题,但是这次它不会阻塞鼠标输入.因此,在启用glassPane的同时,我仍然可以按下位于contentPane上的按钮,我确定它已启用,因为我可以看到我在其上绘制的内容.

I've build a small GUI game in java and at some point I'm using a glassPane to temporarily block all mouseinput. I've used the glassPane before without any problems but this time it won't block the mouseinput. So I can still press a button that resides on the contentPane while the glassPane is enabled, I'm sure it's enabled because I can see the stuff I paint on it.

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

Here is a short piece of runnable code that's shows the problem:

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添加到您的玻璃窗格中,并在所有MouseEvent上消耗事件,例如

i'd try adding a MouseListener to your glasspane, and on all MouseEvents consume the event, such as

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

这篇关于glassPane没有阻止输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆