Components and Containers

In Swing, Components are the visual elements like buttons, labels, and text fields, while Containers hold and organize these components.


Components

Components are instances of classes that inherit from java.awt.Component. Common examples include:

  • JButton
  • JLabel
  • JTextField
  • JCheckBox
  • JComboBox
JButton button = new JButton("Click Me");
JLabel label = new JLabel("Hello");

Containers

Containers are components that can hold other components (including other containers). Examples:

  • JFrame – Top-level window
  • JPanel – Generic lightweight container
  • JDialog – Dialog window
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);

Nesting Components

You can nest components within containers to create structured layouts.

JPanel panel = new JPanel();
panel.add(new JLabel("Name:"));
panel.add(new JTextField(10));