0

I'm trying to add a JComponent to another using java, but just one of them (the top-level) is visible. I need to learn how to create nested panels. I need to learn how to paint what the panel has to show.

Here is my code:

import java.awt.*;

import javax.swing.*;



public class Main {
   public static void main(String[] a) {
      JFrame f = new JFrame();
      f.setTitle("window");
   f.setBounds(100,50,500,300);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   MyComponent mc = new MyComponent(10, 10, 200, 200);
   MyComponent mc2 = new MyComponent(30, 30, 100, 100);
   mc.add(mc2);
   f.getContentPane().add(mc);
   f.setVisible(true);
}
static class MyComponent extends JComponent {

    private int swx;
    private int swy;
    private int nex;
    private int ney;

    public MyComponent(int swx, int swy, int nex, int ney){
        super();
        this.swx = swx;
        this.swy = swy;
        this.nex = nex;
        this.ney = ney;
    }

    public void paint(Graphics g){
        g.drawRect(swx, swy, nex, ney);
    }
}
StackUser
  • 587
  • 6
  • 26
  • 4
    1) `MyComponent` needs to `@Override` the `getPreferredSize()` method to return an appropriate value. This size is examined by the layout manager when deciding how much space to assign the component. Without it, (or child components) the panel or component will return a preferred size of 0x0. 2) See [Detection/fix for the hanging close bracket of a code block](http://meta.stackexchange.com/q/251795/155831) for a problem I could no longer be bothered fixing. 3) For custom painting in any `JComponent`, override the `paintComponent(Graphics g)` method and immediately call the super method. – Andrew Thompson May 16 '15 at 12:05
  • For overlapping content, consider [`OverlayLayout`](http://stackoverflow.com/a/13437388/230513) or [`JLayeredPane`](https://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html). – trashgod May 16 '15 at 12:28
  • BTW - what is your question? – Andrew Thompson May 19 '15 at 03:14

0 Answers0