how do i get the size of a jpanel?

First of all, don’t use TextField. That is an AWT component. For Swing you should be using JTextField.

Swing components don’t have a size until the frame is made visible.

Swing components are responsible for determining their own size. If you want to do custom painting or add random components then you should be overriding the getPreferredSize() method of your component to return its desired size.

@Override
public Dimension getPreferredSize()
{
    return new Dimension(400, 400);
}

Then your constructor can invoke the getPreferredSize() method to get the width/height to be used in your random code.

int x = (int)(Math.random() * getPreferredSize().width); // 랜덤 x좌표 생성
int y = (int)(Math.random() * getPreferredSize().height); // 랜덤 y좌표 생성

Then before you make the frame visible you invoke pack() on the frame and all components will be displayed at their preferred size.

this.pack();
this.setVisible(true); 

Note, why are you trying to display a label at a random position. I also agree with ControlAltDel’s answer that custom painting is a better approach (than using label components). However, the same suggestion I made here would apply there as well. That is you would implement getPreferredSize() and use pack().

If you want to use custom painting, then you would create an ArrayList of object to paint. Then the paintComponent() method would iterate through the ArrayList to paint each object. See: Custom Painting Approaches for an example of this approach.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top