How to set a transparent background of JPanel?

Can JPanels background be set to transparent?

My frame is has two JPanels:

  • Image Panel and
  • Feature Panel.

Feature Panel is overlapping Image Panel. The Image Panel is working as a background and it loads image from a remote URL.

On Feature Panel I want to draw shapes. Now Image Panel cannot be seen due to Feature Panel's background color.

I need to make Feature Panel background transparent while still drawing its shapes and I want Image Panel to be visible (since it is doing tiling and cache function of images).

I'm using two JPanel's, because I need to seperate the image and shape drawing .

Is there a way the overlapping Jpanel have a transparent background?

26
задан Line 21 September 2017 в 13:18
поделиться

3 ответа

В качестве альтернативы рассмотрите Стеклянную панель , описанную в статье Как использовать корневые панели . Вы можете нарисовать содержимое «Feature» в методе paintComponent () стеклянной панели.

Приложение: Работая с GlassPaneDemo , я добавил изображение:

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

и изменил метод paintComponent () стеклянной панели:

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

enter image description here

Как указано здесь , компоненты Swing должны соблюдать свойство непрозрачности ; в этом варианте ImageIcon полностью заполняет BorderLayout.CENTER макета фрейма по умолчанию.

8
ответ дан 28 November 2019 в 07:06
поделиться
 public void paintComponent (Graphics g)
    { 
((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.0f)); // draw transparent background
     super.paintComponent(g);
    ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f)); // turn on opacity
    g.setColor(Color.RED);
    g.fillRect(20, 20, 500, 300);
     } 

Я пытался сделать это таким образом, но он очень мерцающий

2
ответ дан 28 November 2019 в 07:06
поделиться

Вызов setOpaque (false) на верхней JPanel должен работать.

Судя по вашему комментарию, похоже, что рисование Swing где-то не работает -

Во-первых, вы, вероятно, хотели переопределить paintComponent () , а не paint () в каком-либо компоненте у вас есть переопределение paint () в.

Во-вторых, когда вы переопределите paintComponent () , вы сначала захотите вызвать super.paintComponent () первым, чтобы выполнить все стандартные элементы рисования Swing (одним из которых является соблюдение setOpaque () ).

Пример -

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;


public class TwoPanels {
    public static void main(String[] args) {

        JPanel p = new JPanel();
        // setting layout to null so we can make panels overlap
        p.setLayout(null);

        CirclePanel topPanel = new CirclePanel();
        // drawing should be in blue
        topPanel.setForeground(Color.blue);
        // background should be black, except it's not opaque, so 
        // background will not be drawn
        topPanel.setBackground(Color.black);
        // set opaque to false - background not drawn
        topPanel.setOpaque(false);
        topPanel.setBounds(50, 50, 100, 100);
        // add topPanel - components paint in order added, 
        // so add topPanel first
        p.add(topPanel);

        CirclePanel bottomPanel = new CirclePanel();
        // drawing in green
        bottomPanel.setForeground(Color.green);
        // background in cyan
        bottomPanel.setBackground(Color.cyan);
        // and it will show this time, because opaque is true
        bottomPanel.setOpaque(true);
        bottomPanel.setBounds(30, 30, 100, 100);
        // add bottomPanel last...
        p.add(bottomPanel);

        // frame handling code...
        JFrame f = new JFrame("Two Panels");
        f.setContentPane(p);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300, 300);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    // Panel with a circle drawn on it.
    private static class CirclePanel extends JPanel {

        // This is Swing, so override paint*Component* - not paint
        protected void paintComponent(Graphics g) {
            // call super.paintComponent to get default Swing 
            // painting behavior (opaque honored, etc.)
            super.paintComponent(g);
            int x = 10;
            int y = 10;
            int width = getWidth() - 20;
            int height = getHeight() - 20;
            g.drawArc(x, y, width, height, 0, 360);
        }
    }
}
27
ответ дан 28 November 2019 в 07:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: