Transparent JPanel over Canvas (VLCJ)

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

I need a transparent JPanel on top of the canvas. The code below does not work.

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 for the entire frame is the most recent solution (very discouraged)

+4
source share
2 answers

You probably won’t be able to make this work because you mix heavy and light components together.

It used to be impossible to draw lightweight panels over heavyweight components such as Canvas. Since JDK 6 Update 12 and JDK 7 build 19 Java fixed this, and you can overlay 2 correctly, but it has limitations. In particular, in your case, the Overlapping swing component cannot be transparent.

A good description for this, including newer behavior, can be found on this page: Mixing Heavy and Lightweight Components Check the restrictions section for your specific problem.

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

If you change the BackGround class to extend the JPanel instead of Canvas, you get the behavior you need.

+2
source

While AWT is limited, it shouldn't be too difficult to implement something similar with AWT by extending the Container or Component class.

0
source

Source: https://habr.com/ru/post/1336468/


All Articles