0

I want to put multiple JPanel on my JFrame.

public class Rect extends JFrame{

public Rect () {
    gui();
}

class DrawPane extends JPanel{
    private int x=0;

    public DrawPane(int x){
        this.x=x;
    }
    @Override
    public void paintComponent(Graphics g){
       super.paintComponent(g);
       g.fillRect(x, 20, 100, 200);
     }
 }

private void gui() {
    setSize(600, 400);
    addWindowListener(new MyWindowListener());
    getContentPane().add(new DrawPane(20)); //first object
    getContentPane().add(new DrawPane(100)); //second object
    setVisible(true);
}

public static void main(String[] args) {
    new Rect ();
}
}

I am creating two DrawPane-Objects, but only the second appears. What could be the problem? It should'nt be a problem to insert more than one JPanel on a JFrame.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
tamaramaria
  • 173
  • 1
  • 4
  • 17
  • I tried setLayout(new GridBagLayout()); and setLayout(new FlowLayout()); but that doesn't work. Nothing is appearing. – tamaramaria Jun 14 '15 at 16:48
  • 1
    Your `DrawPane` has preferred size of (0, 0). Override `getPreferredSize()` to return something sensible, then the `FlowLayout` version should show two panels. (The original does not, because both of the panels are placed in the center position of `BorderLayout`). – kiheru Jun 14 '15 at 16:52
  • @kiheru Thank you so much. It finally works. I tried in my constructor setPreferredSize(new Dimension(200,200)); and setLayout(new FlowLayou()); – tamaramaria Jun 14 '15 at 16:58

0 Answers0