Search code examples
javaswingawt

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());
    }
}

Solution

  • 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.