Swing - SPLessons

Swing Containers

Chapter 22

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Swing Containers

Swing Containers

shape Description

Swing Containers can be described as a special component that can hold the gathering of components. It will have the capability to provide the gap to put the components. Swing tool kit provided the two types of Swing Containers they are top level containers and low level containers, top level containers are heavy wait Swing Containers such as JFrame, JApplet, JWindow, JDialogue and low level Swing Containers are light weight containers such as JPanel. The commonly used containers are JFrame, JPanel, JWindow.

The difference between the component and container is that component is an object that can provide the visual representation, where as container is also a component that can hold the gathering of components as follows.

shape Conceptual
Figure

shape JPanel

JPanel is a light weight Swing Containers and used to gather the all the components. The basic declaration of JPanel is as follows.

public class JPanel
   extends JComponent
      implements Accessible

shape Example

Below is the source code to build panel in Swing.
JPanelSwing.java

package swing;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
 
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
 

public class JPanelSwing extends JFrame {
     
    private JLabel labelUsername = new JLabel("Enter username: ");
    private JLabel labelPassword = new JLabel("Enter password: ");
    private JTextField textUsername = new JTextField(20);
    private JPasswordField fieldPassword = new JPasswordField(20);
    private JButton buttonLogin = new JButton("Login");
     
    public JPanelSwing() {
        super("JPanel Demo Program");
         
        // create a new panel with GridBagLayout manager
        JPanel newPanel = new JPanel(new GridBagLayout());
         
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.WEST;
        constraints.insets = new Insets(10, 10, 10, 10);
         
        // add components to the panel
        constraints.gridx = 0;
        constraints.gridy = 0;     
        newPanel.add(labelUsername, constraints);
 
        constraints.gridx = 1;
        newPanel.add(textUsername, constraints);
         
        constraints.gridx = 0;
        constraints.gridy = 1;     
        newPanel.add(labelPassword, constraints);
         
        constraints.gridx = 1;
        newPanel.add(fieldPassword, constraints);
         
        constraints.gridx = 0;
        constraints.gridy = 2;
        constraints.gridwidth = 2;
        constraints.anchor = GridBagConstraints.CENTER;
        newPanel.add(buttonLogin, constraints);
         
        // set border for the panel
        newPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(), "Login Panel"));
         
        // add the panel to this frame
        add(newPanel);
         
        pack();
        setLocationRelativeTo(null);
    }
     
    public static void main(String[] args) {
        // set look and feel to the system look and feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
         
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JPanelSwing().setVisible(true);
            }
        });
    }
}

Create a class that should extend JFrame and include labels, text fields, button component.

private JLabel labelUsername = new JLabel("Enter username: ");
    private JLabel labelPassword = new JLabel("Enter password: ");
    private JTextField textUsername = new JTextField(20);
    private JPasswordField fieldPassword = new JPasswordField(20);
    private JButton buttonLogin = new JButton("Login");

Create a constructor, create a panel with GridBagLayout manager.

public JPanelSwing() {
        super("JPanel Demo Program");
JPanel newPanel = new JPanel(new GridBagLayout());

Set the border for the panel and add to the frame.

 newPanel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createEtchedBorder(), "Login Panel"));
         add(newPanel);

Set the look and feel of window application.

try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }

Output:
Output will be as follows.Where created one text field, password field, login button also and created look & feel to the window application as follows.

shape JFrame

JFrame is a top level container of the Swing and heavy weight container. JFrame is an extension form of java.awt.Frame. On which other components will be placed such as panels, text field. The basic declaration of JFrame is as follows.

public class JFrame
   extends Frame
      implements WindowConstants, Accessible

shape Example

Below is the source code to build frame in Swing.

SwingJFrame.java

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

public class SwingJFrame {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingJFrame(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingJFrame  swingContainerDemo = new SwingJFrame();  
      swingContainerDemo.showJFrameDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java JFrame Example");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

      msglabel = new JLabel("Welcome to SPlessons.", JLabel.CENTER);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showJFrameDemo(){
      headerLabel.setText("Container in action: JFrame");   

      final JFrame frame = new JFrame();
      frame.setSize(300, 300);
      frame.setLayout(new FlowLayout());       
      frame.add(msglabel);
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            frame.dispose();
         }        
      });    
      JButton okButton = new JButton("Open a Frame");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("A Frame shown to the user.");
            frame.setVisible(true);
         }
      });
      controlPanel.add(okButton);
      mainFrame.setVisible(true);  
   }
}

Create a class, main frame, labels and create constructor also.

public class SwingJFrame {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

Create the title to the window and set the layout, add listeners to the components.

mainFrame = new JFrame("Java JFrame Example");
mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter()

Create the message label also that should be in center of the window that is “Wrlcome to SPlessons”.

msglabel = new JLabel("Welcome to SPlessons.", JLabel.CENTER);

Set the header label that is”Container in action: JFrame”.

headerLabel.setText("Container in action: JFrame"); 

Create the component button as “open a Frame”. If user click on this button another window will be opened that shows “Welcome To SPlessons” message.

JButton okButton = new JButton("Open a Frame");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {

Output:
Output will be as follows. It shows header label message and status label message is as follows.

When user click on open a frame button “Welcome To SPlessons ” message will be opened.

shape JWindow

JWindow is a low level container and light weight container, by default it uses the BorderLayout. The basic declaration of JWindow is as follows.

public class JWindow
   extends Window
      implements Accessible, RootPaneContainer

shape Example

Below is the source code to build window in Swing.

SwingJWindow.java

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

public class SwingJWindow {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;

   public SwingJWindow(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingJWindow  swingContainerDemo = new SwingJWindow();  
      swingContainerDemo.showJWindowDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    

      statusLabel.setSize(350,100);

      msglabel = new JLabel("Welcome to SPlessons."
         , JLabel.CENTER);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showJWindowDemo(){
      headerLabel.setText("Container in action: JWindow");   
      final MessageWindow window = new MessageWindow(mainFrame, "Welcome to SPlessons.");

      JButton okButton = new JButton("Open a Window");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            window.setVisible(true);
            statusLabel.setText("A Window shown to the user."); 
         }
      });
      controlPanel.add(okButton);
      mainFrame.setVisible(true);  
   }

   class MessageWindow extends JWindow{
      private String message; 

      public MessageWindow(JFrame parent, String 
         message) { 
         super(parent);               
         this.message = message; 
         setSize(300, 300);       
         setLocationRelativeTo(parent);         
      }

      public void paint(Graphics g) 
      { 
         super.paint(g);
         g.drawRect(0,0,getSize().width - 1,getSize().height - 1); 
         g.drawString(message,50,150); 
      } 
   }
}

Create the main method and create the object to the class.

public static void main(String[] args){
      SwingJWindow  swingContainerDemo = new SwingJWindow();  
      swingContainerDemo.showJWindowDemo();

Add grid layout to the main frame and WindowListener to the main frame.

mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent)

Create message label, header label, status label and add this labels to main frame.

headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);
msglabel = new JLabel("Welcome to SPlessons.", JLabel.CENTER);
mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  

Create the open window button and add Listeners to the button, when user click on this button another message window will be opened.

JButton okButton = new JButton("Open a Window");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             

Output:
Output will be as follows.It consists of header message and status message.

When click on “open a window” button then it displays the output as follows.

Summary

shape Key Points

  • JPanel can add colors to the window.
  • Swing Containers can hold the other containers also.
  • JPanel can change the look and feel of the window application.