How to set a transparent background of JPanel?

后端 未结 7 1833
栀梦
栀梦 2020-12-05 04:57

Can JPanels background be set to transparent?

My frame is has two JPanels:

  • Image Panel and
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 05:34

    Alternatively, consider The Glass Pane, discussed in the article How to Use Root Panes. You could draw your "Feature" content in the glass pane's paintComponent() method.

    Addendum: Working with the GlassPaneDemo, I added an image:

    //Set up the content pane, where the "main GUI" lives.
    frame.add(changeButton, BorderLayout.SOUTH);
    frame.add(new JLabel(new ImageIcon("img.jpg")), BorderLayout.CENTER);
    

    and altered the glass pane's paintComponent() method:

    protected void paintComponent(Graphics g) {
        if (point != null) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setComposite(AlphaComposite.getInstance(
                AlphaComposite.SRC_OVER, 0.3f));
            g2d.setColor(Color.yellow);
            g2d.fillOval(point.x, point.y, 120, 60);
        }
    }
    

    As noted here, Swing components must honor the opaque property; in this variation, the ImageIcon completely fills the BorderLayout.CENTER of the frame's default layout.

提交回复
热议问题