我在里面创建了一个JPanel
我放了一个JCheckBox
和两个按钮:
选中复选框时,面板上方会显示一个透明色(alpha = 100)的glassPane,其中包含一个显示String
“正在加载...”的标签,问题是复选框的位置会在显示glassPane:
当我改变框架的尺寸时,glassPane变得不透明,并且在玻璃板下可见的所有组件都变得不可见。
当我将尺寸更改为更小尺寸时,glassPane的背景会变暗并变暗,标签字符串“Loading”变得模糊
以下是我的代码,其灵感来自关于GlassPane GlassPane Tutorial
的Oracle教程package com.training.test;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class Training extends JFrame
{
JCheckBox changeGlass;
JButton button1, button2;
public Training()
{
setBounds(100, 100, 400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Test Glass Pane");
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel glass = (JPanel) getGlassPane();
glass.setOpaque(true);
glass.setBackground(new Color(120, 120, 120, 100));
glass.setLayout(new BorderLayout());
glass.add(new JLabel("Loading ..."));
changeGlass = new JCheckBox("Show Glass Pane", false);
changeGlass.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
glass.setVisible(e.getStateChange() == ItemEvent.SELECTED);
}
});
button1 = new JButton("Select");
button2 = new JButton("Change");
getContentPane().add(changeGlass);
getContentPane().add(button1);
getContentPane().add(button2);
glass.addMouseListener(new MouseListener()
{
public void mouseReleased(MouseEvent e)
{
redispatchEvent(e, (JPanel) getContentPane(), glass);
}
public void mousePressed(MouseEvent e)
{
redispatchEvent(e, (JPanel) getContentPane(), glass);
}
public void mouseExited(MouseEvent e)
{
redispatchEvent(e, (JPanel) getContentPane(), glass);
}
public void mouseEntered(MouseEvent e)
{
redispatchEvent(e, (JPanel) getContentPane(), glass);
}
public void mouseClicked(MouseEvent e)
{
redispatchEvent(e, (JPanel) getContentPane(), glass);
}
});
}
public void redispatchEvent(MouseEvent e, JPanel panel, JPanel glass)
{
Point panelPoint = SwingUtilities.convertPoint(glass, e.getPoint(), panel);
Component c = SwingUtilities.getDeepestComponentAt(panel, (int) panelPoint.getX(), (int) panelPoint.getY());
Point componentPoint = SwingUtilities.convertPoint(panel, panelPoint, c);
if (c != null && c.equals(changeGlass))
{
c.dispatchEvent(new MouseEvent(c, e.getID(), e.getWhen(), e.getModifiers(), (int) componentPoint.getX(), (int) componentPoint.getY(), e.getClickCount(), e
.isPopupTrigger()));
}
else
{
e.consume();
}
}
}
任何人都可以纠正我的错误吗?
答案 0 :(得分:4)
查看问题的可能原因Backgrounds With Transparency以及一些解决方案。基本上因为您使用透明背景,您需要确保自己绘制玻璃窗格的背景。
因此,我将创建一个自定义面板用作您的玻璃窗格,以便您可以管理背景的绘制。然后将此面板设置为框架的玻璃窗格。