Intercepting Events With A Glass Pane
There are a ton of GlassPane examples out there, but it was hard to find a good concise one that did exactly what I wanted. So here are the results of a spike.
This should create a GlassPane that catches all mouse / key events and disappears only when escape is pressed.
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GlassPane extends JPanel { public void install(final RootPaneContainer rootPane) { final Component prevGlassPane = rootPane.getGlassPane(); rootPane.setGlassPane(this); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { Toolkit.getDefaultToolkit().beep(); } }); addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { requestFocus(); } }); addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { Toolkit.getDefaultToolkit().beep(); } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { setVisible(false); rootPane.setGlassPane(prevGlassPane); } } }); setOpaque(false); setVisible(true); repaint(); requestFocus(); } public void paint(Graphics g) { super.paint(g); g.setFont(new Font("Arial", Font.BOLD, 24)); g.setColor(Color.blue); g.drawString("Glass!!!", 110, 140); } public static void main(String[] args) { final JFrame frame = new JFrame("GlassPane Test"); JButton showButton = new JButton("Click here to show glass pane"); showButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new GlassPane().install(frame); } }); frame.getContentPane().setLayout(new BorderLayout(10, 10)); frame.getContentPane().add(BorderLayout.NORTH, new JTextField("TextField1")); frame.getContentPane().add(BorderLayout.CENTER, new JTextField("TextField2")); frame.getContentPane().add(BorderLayout.EAST, showButton); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(575, 300)); frame.setVisible(true); } }
Tags: java