Transparent JPanel over Canvas (VLCJ)

北慕城南 提交于 2019-12-12 12:08:03

问题


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)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4759983/transparent-jpanel-over-canvas-vlcj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!