SilentLucidity
SilentLucidity

Reputation: 410

JFrame is empty when using JPanel

I have 2 Java classes, Game and BaseComponent.

I wanted to draw multiple components in my JFrame, but that doesn't work, since it will only display the last added component.

I think the solution is to add an JPanel, but that still doesn't quite work for me, since no object are being drawn, not even one.

Game:

public class Game
{
  public static void main(String[] args)
  {
    JFrame frame = new JFrame();

    frame.setSize(300, 400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel jpanel = new JPanel();

    JComponent component = new BaseComponent(0,0);
    JComponent component2 = new BaseComponent(1,1);

    jpanel.add(component);
    jpanel.add(component2);
    frame.add(jpanel);

    frame.setVisible(true);
  }
}

BaseComponent:

public class BaseComponent extends JComponent
{
  private int x, y;

  BaseComponent(int i, int y) {
    this.x = i;
    this.y = y;
  }

  @Override
  public Dimension getPreferredSize() {
     return new Dimension((x * 50) + 50, (y * 50) + 50);
  }

  @Override
  protected void paintComponent(Graphics g)
  {
     drawBaseComponent(g, x, y);
  }

  void drawBaseComponent(Graphics g, int x, int y)
  {
     g.setColor(Color.GREEN); 
     g.fillRect(x*50, y*50, 50, 50);
  }
 }

As you can see, this code adds one component to the the panel, which is being added to the JFrame, but it's completely empty;

enter image description here

EDIT: When using prefered size, the application draws two green boxes but the position is not right, I expected them in the place of the two red boxes.

enter image description here

Upvotes: 0

Views: 63

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347332

JPanel uses a FlowLayout by default. This will attempt to size any components to the preferredSize, which is, by default 0x0, which is why, your component "appears" empty.

You will need to supply sizing hints, via getPreferredSize, in order to allow the layout management API to determine the best way to layout your component, for example

public class BaseComponent extends JComponent
{

 private int x, y;

 BaseComponent(int i, int i0) {
    this.x = i;
    this.y = i0;
 }

 @Override
 public Dimension getPreferredSize() {
     return new Dimension((x * 50) + 50, (y * 50) + 50);
 }

 @Override
 protected void paintComponent(Graphics g)
 {
    drawBaseComponent(g, x, y);
 }

 void drawBaseComponent(Graphics g, int xLeft, int yTop)
 {
   g.setColor(Color.GREEN); 
   g.fillRect(x*50, y*50, 50, 50);
 }
}

Upvotes: 1

Related Questions