Using a JPanel to help lay out components. - Java Swing

Java examples for Swing:JPanel

Description

Using a JPanel to help lay out components.

Demo Code

import java.awt.GridLayout;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;

class PanelFrame extends JFrame 
{
   private final JPanel buttonJPanel; // panel to hold buttons
   private final JButton[] buttons; 

   // no-argument constructor
   public PanelFrame()
   {/*from ww w .j a v  a2  s  .co m*/
      super("Panel Demo");
      buttons = new JButton[5]; 
      buttonJPanel = new JPanel(); 
      buttonJPanel.setLayout(new GridLayout(1, buttons.length));

      // create and add buttons
      for (int count = 0; count < buttons.length; count++) 
      {
         buttons[count] = new JButton("Button " + (count + 1));
         buttonJPanel.add(buttons[count]); // add button to panel
      } 

      add(buttonJPanel, BorderLayout.SOUTH); // add panel to JFrame
   } 
}

public class Main extends JFrame 
{
   public static void main(String[] args)
   { 
      PanelFrame panelFrame = new PanelFrame(); 
      panelFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      panelFrame.setSize(450, 200); 
      panelFrame.setVisible(true); 
   } 
}

Related Tutorials