在JLayer上添加固定大小的JPanel

时间:2012-12-03 16:10:10

标签: java swing user-interface jpanel jlayer

关注Oracle's Myopia guide,我有一个简单的JPanel,它作为JFrame添加到JLayer。很简单,这会模糊JPanel的组件。但是,我正在尝试在此JPanel之上添加第二个JPanel(意味着它不会模糊)。

简单JPanel以及Main-method:

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);
    }
}

这将产生以下结果:

enter image description here

我尝试将第二个JPanel添加到第一个JFrame 之后,这只会导致第二个面板占用所有空间。使用各种布局管理器和set-Maximum/Preferred-size()方法将无济于事。也不会使第二个面板背景透明。

如何添加固定大小超过JPanel JLayer,从而允许第一个面板的一部分出现(仍然模糊)?

1 个答案:

答案 0 :(得分:1)

根据您的评论,您想要在加载图片时模糊数据,我建议您使用对话框。您可以将未模糊的面板放在对话框上,使用setUndecorated(true)关闭它的框架和标题栏,并将其默认关闭行为设置为DO_NOTHING_ON_CLOSE,以防止用户在加载应用程序之前关闭对话框。这将位于模糊面板的顶部,但由于它不是BlurLayerUI的一部分,因此不会模糊。