Search code examples
javaswingpaintcomponent

Java Superpose two JPanels


I'm working on Java 7 for a desktop application using mostly swing.

I would like to Superpose two JPanels. Basically, I have a JPanel (1) in which I would like to draw some stuff (with paintComponent()) and on top of it, I'd like to display another JPanel (2) filled with a JScrollPane (3) filled with a Jtable (4).

The Components (2, 3 & 4) would have a transparent background to let see the painted Component on the JPanel 1.

Any idea how to organize/do/implement this ?

Thank you !


Solution

  • I found out the proper way.

    My Jpanel (1) is a borderLayout and has a paintComponent(gg) method which draw several things. I add to that panel a JScrollPane (3) and inside it a Jtable (4).

    The idea is that 3 & 4 have a transparent background.

    For a JScrollpane and a JPanel:

    • jp.setOpaque(false)

    For a JTable, it is more difficult. The background of the JT has to be opaque and the background of each cell has to be transparent using R,G,B,A. To make it opaque, precess as with a Jpanel. Then add a CellRenderer to the JTable and (for each cell) setBackground(new Color(0,0,0,0));

    I then had some issues when I scrolled in the ScrollPane. You will have to add a visibility listener to the JScrollPane. When to JScrollPane visibility change, repaint() the Jpanel (1).

    This way it's workings but it's not fluid. Even with a new generation untrabook(2014). (I only draw an image from a file in the Jpanel 1)

    So, I hope there will be some better solutions.

    Update : see this : Add background image in JTable