glassPane is not blocking input
Asked Answered
H

1

7

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);
    }
}
Hydrofoil answered 23/4, 2011 at 1:19 Comment(1)
+1 for the SSCCETrustful
T
4

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();
}
Treadway answered 23/4, 2011 at 2:13 Comment(1)
thanks! that worked, I didn't even need the comsume() method. Although it did create a new problem. I have a JCombobox on the glassPane and since I added the mouselisteners, I can't scroll through the list or select something in the list anymore with the mouse.Hydrofoil

© 2022 - 2024 — McMap. All rights reserved.