Pergunta

I know that a similar question was posted before, but there was no answer or example code.

I need a transparent JPanel on top of a canvas. The code posted below is not working

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class Main {
    private static class Background extends Canvas{
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.setColor(Color.RED);
            g.drawOval(10, 10, 20, 20);
        }
    }

    private static class Transparent extends JPanel {

        public Transparent() {
            setOpaque(false);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.GREEN);
            g.drawOval(20, 20, 20, 20);
        }
    }

    public static void main(String[] args){
        JFrame frame = new JFrame();
        JLayeredPane layered = new JLayeredPane();
        Background b = new Background();
        Transparent t = new Transparent();

        layered.setSize(200, 200);
        b.setSize(200, 200);
        t.setSize(200, 200);

        layered.setLayout(new BorderLayout());
        layered.add(b, BorderLayout.CENTER, 1);
        layered.add(t, BorderLayout.CENTER, 0);

        frame.setLayout(new BorderLayout());
        frame.add(layered, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setVisible(true);
    }
}

Using the GlassPane property of the entire frame is the very last solution (highly discouraged)

Foi útil?

Solução

You probably will not be able to get this to work because you are mixing heavyweight and lightweight components together.

In the past it used to be impossible to draw lightweight panels over heavyweight components like a Canvas. Since JDK 6 Update 12 and JDK 7 build 19 Java has corrected this and you can overlap the 2 correctly however it comes with limitations. Specifically in your case the Overlapping swing component cannot be transparent.

A good description for this including the newer behaviour can be found on this page: Mixing Heavyweight and Lightweight Components Check the limitations section for your specific problem.

I don't think using the GlassPane will help as it is also lightweight.

If you change the BackGround class to extend JPanel instead of Canvas you will get the behaviour you want.

Outras dicas

While AWT is limited it should not be too hard to implement something similar with AWT itself by extending either the Container or Component class.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top