我里面有一个 JFrame 和一个 JPanel 层次结构,我想实现一个内部面板,我可以让它看起来“禁用”(而其他面板不改变),也就是说,用半透明的灰色层覆盖它并拦截所有发送到此面板的鼠标甚至键盘事件。我一直在寻找解决方案,但还没有真正找到一个好的解决方案。
我最接近解决方案的是当我使用 JRootPane 时,每当我想要禁用它时,我都会让它的玻璃窗格可见。玻璃板已设置为不透明且具有半透明背景。
我尝试的一个简单示例:
public class Test extends JFrame {
private final JPanel jPanel;
public Test() {
jPanel = new JPanel();
final JButton jButton = new JButton("Hidden");
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("hidden is clicked!");
}
});
final JRootPane jRootPane = new JRootPane();
jPanel.add(jRootPane);
final JPanel glassPane = new JPanel();
final JButton jButton2 = new JButton();
jButton2.addActionListener(new ActionListener() {
private boolean visible = true;
@Override
public void actionPerformed(ActionEvent e) {
glassPane.setVisible(visible = !visible);
}
});
jPanel.add(jButton2);
jRootPane.getContentPane().add(new JScrollPane(jButton));
glassPane.setBackground(new Color(0.5f, 0.5f, 0.5f, 0.2f));
glassPane.setOpaque(true);
jRootPane.setGlassPane(glassPane);
glassPane.setVisible(true);
getContentPane().add(jPanel);
}
public static void main(String[] strings) {
final Test test = new Test();
test.pack();
test.setVisible(true);
}
}
但问题是,即使玻璃在内容顶部可见,它也不会按照应有的方式拦截获取内容的事件,如此处所述。