Java JPanel hold components

Description

Java JPanel hold components

// Using a JPanel to help lay out components.
import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

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

  public Main() {
    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
    }//  w  w w . j av  a  2s  . c  om

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

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



PreviousNext

Related