What is the importance of the Container class in Java?


Container

  • A Container class can be described as a special component that can hold the gathering of the components.
  • There are two types of Swing Containers, they are top-level containers and low-level containers.
  • Top-Level containers are heavyweight containers such as JFrame, JApplet, JWindow, and JDialog.
  • Low-Level containers are lightweight containers such as JPanel.
  • The most commonly used containers are JFrame, JPanel and JWindow.
  • The important methods of the Container class are add(), invalidate() and validate().

Example

import java.awt.*;
import javax.swing.*;

public class ContainerTest extends JFrame { // top-level container
   JPanel panel; // low-level container
   JTextField field;
   JButton btn;
   public ContainerTest() {
      setTitle("Container Test");
      panel = new JPanel();
      field = new JTextField(20);
      panel.add(field);
      btn = new JButton("Submit");
      panel.add(btn);
      add(panel, BorderLayout.CENTER);

      setSize(350, 275);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) {
      new ContainerTest();
   }
}

Output


raja
Published on 10-Jul-2019 17:44:12
Advertisements