Academic Java    Java Tutorial  >  Swing  >  JPanel.setPreferredSize()

JPanel.setPreferredSize() Example

Java JPanel.setPreferredSize EXAMPLE output This JPanel example shows two JPanels.

The size of a JPanel is usually dictated by its contents. JPanel is a subclass of JComponent and therefore also a subclass of Container. Its size will normally depend on its layout manager and components added into it. The default sizing can, however, be changed by using its inherited method setPreferredSize() method.

Here we show the previous example, but altered by use of the setPreferredSize(). Notice that the size of the two panels accords with the size they were set to.
// JPanel Size Example using setPreferredSize()
import java.awt.*;
import javax.swing.*;

class JPanelSizeExample {

   public static void main(String[] args) {

      JPanel p0 = new JPanel();
      p0.setBackground(Color.pink);
      p0.setPreferredSize(new Dimension(60,100));

      for(int i=0;i<3;++i) p0.add(new JLabel("label "+i));

      JPanel p1 = new JPanel();
      p1.setBackground(Color.magenta);
      p1.setPreferredSize(new Dimension(80,150));

      for(int i=0;i<3;++i) p1.add(new JButton("button "+i));

      JFrame frame = new JFrame();
      Container cp = frame.getContentPane();
      cp.setLayout(new FlowLayout());
      cp.add(p0);
      cp.add(p1);

      frame.setSize(300,300);
      frame.setBackground(Color.black);
      frame.setVisible(true);
   }
}


* JPanel Examples