In Java, what is the default JPanel height and width?

I have created class as below. When I create an object called drawpanel of this class and add to the frame using frame.getContentPane().add(BorderLayout.CENTER, drawpanel), I get a rectangle with black background as expected. Does it mean that the Panel's this.getWidth and this.getHeight by default has the same the height and width of the Frame (which is why it fills up the entire frame with black colour) ?

One other way I want to reframe my question is - If I create a custom widget by extending JPanel, and when this custom widget is instantiated, what is its default height and width ?

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g){
    g.fillRect(0, 0, this.getWidth(), this.getHeight());
    }
}

Upvotes: 1

Views: 3430

Answers (4)

Paul Frischknecht
Paul Frischknecht

Reputation: 21

Knowing the preferred size of a JPanel is quite important when you are dealing with a GridBagLayout which respects the preferred size property:

new JPanel().getPreferredSize() == java.awt.Dimension[width=10,height=10]

in words: a JPanel's preferred size is nonzero.

Because of this, putting e.g. two JPanels into a GridBagLayout with certain weights will only scale by the relative percentages of the weights of the cells if you explicitly override the preferred size back to 0:

p = new JPanel(); p.setPreferredSize(new Dimension(0, 0));

Upvotes: 0

Crazyjavahacking
Crazyjavahacking

Reputation: 9677

JPanel have default size 0 width and 0 height.

You can set the size:

  • manually: panel.setSize(), panel.setPreferredSize()
  • automatically: panel.pack()

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168815

Does it mean that the Panel's this.getWidth and this.getHeight by default has the same the height and width of the Frame (which is why it fills up the entire frame with black colour) ?

No, it means the frame has a layout/constraint (BorderLayout/CENTER) that will stretch the component to whatever size that will fill it.

If I create a custom widget by extending JPanel, and when this custom widget is instantiated, what is its default height and width ?

0x0 (without any components laid out).


The panel in which custom painting is done should return a preferred size for the content. Once added to the frame, call the pack() method and it will be the exact size it need to be in order to honor the preferred size of the component(s).

Upvotes: 1

Distjubo
Distjubo

Reputation: 1009

I think the JPanel by itself has a prefered size of 0,0. But if you add some components to it with a higher prefered size, its prefered size will not be 0.

Upvotes: 0

Related Questions