【发布时间】:2012-12-03 16:10:10
【问题描述】:
在Oracle's Myopia guide 之后,我有一个简单的JPanel,它作为JLayer 添加到JFrame。很简单,这模糊了JPanel 的组件。但是,我正在尝试在此 JPanel 上方添加第二个 JPanel(这意味着它不会变得模糊)。
简单的JPanel 连同主方法:
public class ContentPanel extends JPanel {
public ContentPanel() {
setLayout(new BorderLayout());
add(new JLabel("Hello world, this is blurry!"), BorderLayout.NORTH);
add(new JLabel("Hello world, this is blurry!"), BorderLayout.CENTER);
add(new JButton("Blurry button"), BorderLayout.SOUTH);
}
public static void main(String[] args) {
JFrame f = new JFrame("Foo");
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
LayerUI<JComponent> layerUI = new BlurLayerUI();
JPanel panel = new ContentPanel();
JLayer<JComponent> jlayer = new JLayer<JComponent>(panel, layerUI);
f.add(jlayer);
f.setVisible(true);
}
}
BlurLayerUI 模糊了它的“孩子”:
class BlurLayerUI extends LayerUI<JComponent> {
private BufferedImage mOffscreenImage;
private BufferedImageOp mOperation;
public BlurLayerUI() {
float ninth = 1.0f / 9.0f;
float[] blurKernel = { ninth, ninth, ninth, ninth, ninth, ninth, ninth,
ninth, ninth };
mOperation = new ConvolveOp(new Kernel(3, 3, blurKernel),
ConvolveOp.EDGE_NO_OP, null);
}
@Override
public void paint(Graphics g, JComponent c) {
int w = c.getWidth();
int h = c.getHeight();
if (w == 0 || h == 0) {
return;
}
// Only create the offscreen image if the one we have
// is the wrong size.
if (mOffscreenImage == null || mOffscreenImage.getWidth() != w
|| mOffscreenImage.getHeight() != h) {
mOffscreenImage = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
}
Graphics2D ig2 = mOffscreenImage.createGraphics();
ig2.setClip(g.getClip());
super.paint(ig2, c);
ig2.dispose();
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(mOffscreenImage, mOperation, 0, 0);
}
}
这将产生以下内容:
我试图简单地将第二个JPanel 添加到JFrame 在第一个之后,这只会导致第二个面板占用所有空间。使用各种布局管理器和set-Maximum/Preferred-size() 方法不会有任何好处。也不会使第二个面板背景透明。
如何在JLayer上方添加一个固定大小的JPanel,从而让第一个面板的一部分出现(仍然模糊)?
【问题讨论】:
-
为什么不直接更改模糊的大小以仅包含您想要的组件?
-
@DavidKroukamp 将出现在所有其他内容上的面板包含加载图像和其他一些元素,并且会在需要时淡入/淡出。因此,作为其中的一部分,所有其他面板都将被模糊,因此 JLayer。
-
@Zar,常规内容真的需要模糊吗?我有点困惑为什么用户需要在你的加载图像后面看到一个模糊的应用程序。
标签: java swing user-interface jpanel jlayer