2

Okay so I have spent a lot of time searching for some answers to my problem and I have had very little luck. I am trying to add a graphic that I have painted to a JPanel and then adding the JPanel to the JFrame. here is my code:

import java.awt.*;
import javax.swing.*;

public class Testing
{  
   public static void main(String[] args)
{  
  JFrame f = new JFrame("JFrame with a JPanel");
  f.setSize(500,500);
  JLabel l1 = new JLabel("Hello !");
  JPanel p1 = new JPanel();
  JPanel p2 = new JPanel();
  DrawBox dB = new DrawBox(400,200,20,20);

  p1.add(l1);
  p2.add(dB);
  f.add(p1,BorderLayout.PAGE_END);
  f.add(p2,BorderLayout.CENTER);    
  //f.add(dB);                      //Adding directly to the JFrame works fine
  f.setVisible(true);
  }
}

Next is the class that creates the graphic

public class DrawBox extends JPanel {

int xVal = 0;
int yVal = 0;
int width = 0;
int height = 0;

public DrawBox(int x, int y, int w, int h) {
    xVal = x;
    yVal = y;
    width = w;
    height = h;
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawRect(xVal, yVal, width, height);
}

}

If I add DrawBox directly to the the JFrame it seems to work fine. However if I try to add more than one graphic directly to JFrame only one of them will show.

1 Answers1

3

From your comment

//f.add(dB); //Adding directly to the JFrame works fine

It works because the BorderLayout of the frame doesnt respect preferred sizes. It will stretch the drawing panel to fit.

On the other hand when you add wrap the drawing panel in another panel, the wrapper panel has a default FlowLayout that does respect preferred sizes. Your drawing panel has a 0x0 preferred size if you don't explicitly set it by overriding getPreferredSize()

@Override
public Dimension getPreferredSize() {
    return new Dimension( ... , ... );
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720