0

I am attempting to overlay a smaller panel (sub) over a larger panel (parent). The dimensions of sub are smaller than that of parent.

JPanel sub = new JPanel();
JPanel parent = new CustomPanel();

I would like to override parent's paintComponent method to draw sub in the top left hand corner with an offset of 5 pixels from the top and left sides. It would look something like this:

class CustomPanel extends JPanel() {

    JPanel sub = null;

    public CustomPanel(JPanel sub) {
        this.sub = sub;
    }

    @Override
    public void paintComponent(Graphics g) {
        this.paintComponent(g);
        // TODO: Here is where I would call something like sub.paint();
        // However, I want sub to "start its paint" 5 pixels inside of
        // parent's dimensions. How do I specify this?

Is it possible to tell sub to paint itself at a specific location? Terrible idea?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
sdasdadas
  • 23,917
  • 20
  • 63
  • 148

1 Answers1

2

Why don't you just setLayout(null) on the parent panel and then, before adding the sub panel to parent , set it's position and dimensions using it's setBounds method. This way there is no need to use paintComponent for positioning the sub panel.

Is case you parent panel should have specific layout with other components and sub should overlay all that, look into JLayer(Java 7) / JXLayer(Java 6).

Third solution can be using JLayeredPane.

Eugene Ryzhikov
  • 17,131
  • 3
  • 38
  • 60
  • The problem being that `parent` contains a non-trivial layout of components as well. The overlay (`sub`) should draw over them - but I don't think I can get away from positioning them all manually. – sdasdadas Apr 12 '13 at 02:14
  • Thank you for all of the answers - I have played with LayeredPane before but it's been a little while and I can't instantly recall why I was having troubles with it. I'll try it again, but hopefully there's also a way to perform the paint manually. – sdasdadas Apr 12 '13 at 02:19
  • With JLayer you can paint over the parent panel – Eugene Ryzhikov Apr 12 '13 at 02:20
  • You were right and I apologize - this is a duplicate. I had this problem in February as well... http://stackoverflow.com/questions/14779401/is-it-possible-to-specify-depth-in-miglayout – sdasdadas Apr 12 '13 at 02:29