HTML

html content help to improve the coding

Thursday, 13 November 2014

SWING MouseMotionListener Interface

SWING MouseMotionListener Interface

Introduction

The interfaceMouseMotionListener is used for receiving mouse motion events on a component. The class that process mouse motion events needs to implements this interface.

Class declaration

Following is the declaration for java.awt.event.MouseMotionListener interface:
public interface MouseMotionListener
extends EventListener

Interface methods

S.N.Method & Description
1void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
2void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Methods inherited

This class inherits methods from the following interfaces:
  • java.awt.event.EventListener

MouseMotionListener Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingListenerDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showMouseMotionListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMouseMotionListenerDemo(){
      headerLabel.setText("Listener in action: MouseMotionListener");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseMotionListener(new CustomMouseMotionListener());
      
      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);        
      panel.add(msglabel);

      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }

   class CustomMouseMotionListener implements MouseMotionListener {
      public void mouseDragged(MouseEvent e) {
         statusLabel.setText("Mouse Dragged: ("+e.getX()+", "+e.getY() +")");
      }

      public void mouseMoved(MouseEvent e) {
         statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
      }    
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo
Verify the following output
SWING MouseMotionListener

SWING FocusListener Interface

Introduction

The interfaceFocusListener is used for receiving keyboard focus events. The class that process focus events needs to implements this interface.

Class declaration

Following is the declaration for java.awt.event.FocusListener interface:
public interface FocusListener
extends EventListener

Interface methods

S.N.Method & Description
1void focusGained(FocusEvent e)
Invoked when a component gains the keyboard focus.
2void focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.

Methods inherited

This class inherits methods from the following interfaces:
  • java.awt.event.EventListener

FocusListener Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingListenerDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingListenerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
      swingListenerDemo.showFocusListenerDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showFocusListenerDemo(){

      headerLabel.setText("Listener in action: FocusListener");      
      JButton okButton = new JButton("OK");
      JButton cancelButton = new JButton("Cancel");
   
      okButton.addFocusListener(new CustomFocusListener());  
      cancelButton.addFocusListener(new CustomFocusListener());  
   
      controlPanel.add(okButton);
      controlPanel.add(cancelButton);     
      mainFrame.setVisible(true);  

   }

   class CustomFocusListener implements FocusListener{
      public void focusGained(FocusEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " gained focus. ");
      }

      public void focusLost(FocusEvent e) {
         statusLabel.setText(statusLabel.getText() 
         + e.getComponent().getClass().getSimpleName() + " lost focus. ");
      }
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingListenerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingListenerDemo
Verify the following output
SWING focusListener

SWING Event Adapters

Adapters are abstract classes for receiving various events. The methods in these classes are empty. These classes exists as convenience for creating listener objects.

SWING FocusAdapter Class

Introduction

The class FocusAdapter is an abstract (adapter) class for receiving keyboard focus events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.FocusAdapter class:
public abstract class FocusAdapter
   extends Object
      implements FocusListener

Class constructors

S.N.Constructor & Description
1FocusAdapter()

Class methods

S.N.Method & Description
1void focusGained(FocusEvent e)
Invoked when a component gains the keyboard focus.
2focusLost(FocusEvent e)
Invoked when a component loses the keyboard focus.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

FocusAdapter Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingAdapterDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showFocusAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showFocusAdapterDemo(){

      headerLabel.setText("Listener in action: FocusAdapter");      

      JButton okButton = new JButton("OK");
      JButton cancelButton = new JButton("Cancel");
      okButton.addFocusListener(new FocusAdapter(){
         public void focusGained(FocusEvent e) {
            statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() 
            + " gained focus. ");
         }
      });  
      
      cancelButton.addFocusListener(new FocusAdapter(){
         public void focusLost(FocusEvent e) {
            statusLabel.setText(statusLabel.getText() 
            + e.getComponent().getClass().getSimpleName() 
            + " lost focus. ");
         }
      });  
      
      controlPanel.add(okButton);
      controlPanel.add(cancelButton);     
      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo
Verify the following output
SWING FocusAdapter

SWING KeyAdapter Class

Introduction

The class KeyAdapter is an abstract (adapter) class for receiving keyboard events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.KeyAdapter class:
public abstract class KeyAdapter
   extends Object
      implements KeyListener

Class constructors

S.N.Constructor & Description
1KeyAdapter()

Class methods

S.N.Method & Description
1void keyPressed(KeyEvent e)
Invoked when a key has been pressed.
2void keyReleased(KeyEvent e)
Invoked when a key has been released.
3void keyTyped(KeyEvent e)
Invoked when a key has been typed.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

KeyAdapter Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showKeyAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showKeyAdapterDemo(){
      headerLabel.setText("Listener in action: KeyAdapter");      

      final JTextField textField = new JTextField(10);

      textField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {                
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
               statusLabel.setText("Entered text: " 
               + textField.getText());
            }
         }        
      });
      JButton okButton = new JButton("OK");
      okButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            statusLabel.setText("Entered text: " 
            + textField.getText());                
         }
      });

      controlPanel.add(textField);
      controlPanel.add(okButton);    
      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo
Verify the following output
SWING KeyAdapter

SWING MouseAdapter Class

Introduction

The class MouseAdapter is an abstract (adapter) class for receiving mouse events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.MouseAdapter class:
public abstract class MouseAdapter
   extends Object
      implements MouseListener, MouseWheelListener, MouseMotionListener

Class constructors

S.N.Constructor & Description
1MouseAdapter()

Class methods

S.N.Method & Description
1void mouseClicked(MouseEvent e)
Invoked when the mouse button has been clicked (pressed and released) on a component.
2void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
3void mouseEntered(MouseEvent e)
Invoked when the mouse enters a component.
4void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.
5void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.
6void mousePressed(MouseEvent e)
Invoked when a mouse button has been pressed on a component.
7void mouseReleased(MouseEvent e)
Invoked when a mouse button has been released on a component.
8void mouseWheelMoved(MouseWheelEvent e)
Invoked when the mouse wheel is rotated.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

MouseAdapter Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtAdapterDemo  awtAdapterDemo = new AwtAdapterDemo();  
      swingAdapterDemo.showMouseAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMouseAdapterDemo(){
      headerLabel.setText("Listener in action: MouseAdapter");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e) {
            statusLabel.setText("Mouse Clicked: ("
            +e.getX()+", "+e.getY() +")");
         }                
      });

      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);
      
      msglabel.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e) {
            statusLabel.setText("Mouse Clicked: ("
            +e.getX()+", "+e.getY() +")");
         }                
      });
      panel.add(msglabel);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo
Verify the following output
SWING MouseAdapter

SWING MouseMotionAdapter Class

Introduction

The class MouseMotionAdapter is an abstract (adapter) class for receiving mouse motion events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.MouseMotionAdapter class:
public abstract class MouseMotionAdapter
   extends Object
      implements MouseMotionListener

Class constructors

S.N.Constructor & Description
1MouseMotionAdapter()

Class methods

S.N.Method & Description
1void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
2void mouseMoved(MouseEvent e)
Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

MouseMotionAdapter Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showMouseMotionAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMouseMotionAdapterDemo(){
      headerLabel.setText("Listener in action: MouseMotionAdapter");      

      JPanel panel = new JPanel();      
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.addMouseMotionListener(new MouseMotionAdapter(){
         public void mouseMoved(MouseEvent e) {
            statusLabel.setText("Mouse Moved: ("+e.getX()+", "+e.getY() +")");
         }                
      });

      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo
Verify the following output
SWING MouseMotionAdapter

SWING WindowAdapter Class

Introduction

The class WindowAdapter is an abstract (adapter) class for receiving window events. All methods of this class are empty. This class is convenience class for creating listener objects.

Class declaration

Following is the declaration for java.awt.event.WindowAdapter class:
public abstract class WindowAdapter
   extends Object
      implements WindowListener, WindowStateListener, WindowFocusListener

Class constructors

S.N.Constructor & Description
1WindowAdapter()

Class methods

S.N.Method & Description
1void windowActivated(WindowEvent e)
Invoked when a window is activated.
2void windowClosed(WindowEvent e)
Invoked when a window has been closed.
3void windowClosing(WindowEvent e)
Invoked when a window is in the process of being closed.
4void windowDeactivated(WindowEvent e)
Invoked when a window is de-activated.
5void windowDeiconified(WindowEvent e)
Invoked when a window is de-iconified.
6void windowGainedFocus(WindowEvent e)
Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events.
7void windowIconified(WindowEvent e)
Invoked when a window is iconified.
8void windowLostFocus(WindowEvent e)
Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents.
9void windowOpened(WindowEvent e)
Invoked when a window has been opened.
10void windowStateChanged(WindowEvent e)
Invoked when a window state is changed.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

WindowAdapter Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingAdapterDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingAdapterDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingAdapterDemo  swingAdapterDemo = new SwingAdapterDemo();        
      swingAdapterDemo.showWindowAdapterDemo();
   }

   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   
   private void showWindowAdapterDemo(){
      headerLabel.setText("Listener in action: WindowAdapter");      

      JButton okButton = new JButton("OK");

      final JFrame aboutFrame = new JFrame();
      aboutFrame.setSize(300,200);;
      aboutFrame.setTitle("WindowAdapter Demo");
      aboutFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
               aboutFrame.dispose();
         }        
      });    
      JLabel msglabel 
      = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
      ,JLabel.CENTER);
   aboutFrame.add(msgLabel);
      aboutFrame.setVisible(true);
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingAdapterDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingAdapterDemo
Verify the following output
SWING WindowAdapter

SWING Layouts

Introduction

Layout means the arrangement of components within the container. In other way we can say that placing the components at a particular position within the container. The task of layouting the controls is done automatically by the Layout Manager.

Layout Manager

The layout manager automatically positions all the components within the container. If we do not use layout manager then also the components are positioned by the default layout manager. It is possible to layout the controls by hand but it becomes very difficult because of the following two reasons.
  • It is very tedious to handle a large number of controls within the container.
  • Oftenly the width and height information of a component is not given when we need to arrange them.
Java provide us with various layout manager to position the controls. The properties like size,shape and arrangement varies from one layout manager to other layout manager. When the size of the applet or the application window changes the size, shape and arrangement of the components also changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the application window.
The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface.

SWING LayoutManager Interface

Introduction

The interfaceLayoutManager is used to define the interface for classes that know how to lay out Containers.

Class declaration

Following is the declaration for java.awt.LayoutManager interface:
public interface LayoutManager

Interface methods

S.N.Method & Description
1void addLayoutComponent(String name, Component comp)
If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
2void layoutContainer(Container parent)
Lays out the specified container.
3Dimension minimumLayoutSize(Container parent)
Calculates the minimum size dimensions for the specified container, given the components it contains.
4Dimension preferredLayoutSize(Container parent)
Calculates the preferred size dimensions for the specified container, given the components it contains.
5void removeLayoutComponent(Component comp)
Removes the specified component from the layout.

SWING LayoutManager2 Interface

Introduction

The interfaceLayoutManger is used to define the interface for classes that know how to lay out Containers based on a layout constraints object.

Class declaration

Following is the declaration for java.awt.LayoutManager2 interface:
public interface LayoutManger2
   extends LayoutManager

Interface methods

S.N.Method & Description
1void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to the layout, using the specified constraint object.
2float getLayoutAlignmentX(Container target)
Returns the alignment along the x axis.
3float getLayoutAlignmentY(Container target)
Returns the alignment along the y axis.
4void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
5Dimension maximumLayoutSize(Container target)
Calculates the maximum size dimensions for the specified container, given the components it contains.

SWING BorderLayout Class

Introduction

The class BorderLayout arranges the components to fit in the five regions: east, west, north, south and center. Each region is can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER.

Class declaration

Following is the declaration for java.awt.BorderLayout class:
public class BorderLayout
   extends Object
      implements LayoutManager2, Serializable

Field

Following are the fields for java.awt.BorderLayout class:
  • static String AFTER_LAST_LINE -- Synonym for PAGE_END.
  • static String AFTER_LINE_ENDS -- Synonym for LINE_END.
  • static String BEFORE_FIRST_LINE -- Synonym for PAGE_START.
  • static String BEFORE_LINE_BEGINS -- Synonym for LINE_START.
  • static String CENTER -- The center layout constraint (middle of container).
  • static String EAST -- The east layout constraint (right side of container).
  • static String LINE_END -- The component goes at the end of the line direction for the layout.
  • static String LINE_START -- The component goes at the beginning of the line direction for the layout.
  • static String NORTH -- The north layout constraint (top of container).
  • static String PAGE_END -- The component comes after the last line of the layout's content.
  • static String PAGE_START -- The component comes before the first line of the layout's content.
  • static String SOUTH -- The south layout constraint (bottom of container).
  • static String WEST -- The west layout constraint (left side of container).

Class constructors

S.N.Constructor & Description
1BorderLayout()
Constructs a new border layout with no gaps between components.
2BorderLayout(int hgap, int vgap)
Constructs a border layout with the specified gaps between components.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to the layout, using the specified constraint object.
2void addLayoutComponent(String name, Component comp)
If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
3int getHgap()
Returns the horizontal gap between components.
4float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
5float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
6int getVgap()
Returns the vertical gap between components.
7void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
8void layoutContainer(Container target)
9Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the specified target container.
10Dimension minimumLayoutSize(Container target)
Determines the minimum size of the target container using this layout manager.
11Dimension preferredLayoutSize(Container target)
Determines the preferred size of the target container using this layout manager, based on the components in the container.
12void removeLayoutComponent(Component comp)
Removes the specified component from this border layout.
13void setHgap(int hgap)
Sets the horizontal gap between components.
14void setVgap(int vgap)
Sets the vertical gap between components.
15String toString()
Returns a string representation of the state of this border layout.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

BorderLayout Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingLayoutDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showBorderLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showBorderLayoutDemo(){
      headerLabel.setText("Layout in action: BorderLayout");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      BorderLayout layout = new BorderLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      panel.setLayout(layout);        
   
      panel.add(new JButton("Center"),BorderLayout.CENTER);
      panel.add(new JButton("Line Start"),BorderLayout.LINE_START); 
      panel.add(new JButton("Line End"),BorderLayout.LINE_END);
      panel.add(new JButton("East"),BorderLayout.EAST);   
      panel.add(new JButton("West"),BorderLayout.WEST); 
      panel.add(new JButton("North"),BorderLayout.NORTH); 
      panel.add(new JButton("South"),BorderLayout.SOUTH); 

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo
Verify the following output
SWING BorderLayout

SWING CardLayout Class

Introduction

The class CardLayout arranges each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards.

Class declaration

Following is the declaration for java.awt.CardLayout class:
public class CardLayout
   extends Object
      implements LayoutManager2, Serializable

Class constructors

S.N.Constructor & Description
1CardLayout()
Creates a new card layout with gaps of size zero.
2CardLayout(int hgap, int vgap)
Creates a new card layout with the specified horizontal and vertical gaps.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to this card layout's internal table of names.
2void addLayoutComponent(String name, Component comp)
If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
3void first(Container parent)
Flips to the first card of the container.
4int getHgap()
Gets the horizontal gap between components.
5float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
6float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
7int getVgap()
Gets the vertical gap between components.
8void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
9void last(Container parent)
Flips to the last card of the container.
10void layoutContainer(Container parent)
Lays out the specified container using this card layout.
11Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the specified target container.
12Dimension minimumLayoutSize(Container parent)
Calculates the minimum size for the specified panel.
13void next(Container parent)
Flips to the next card of the specified container.
14Dimension preferredLayoutSize(Container parent)
Determines the preferred size of the container argument using this card layout.
15void previous(Container parent)
Flips to the previous card of the specified container.
16void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
17void setHgap(int hgap)
Sets the horizontal gap between components.
18void setVgap(int vgap)
Sets the vertical gap between components.
19void show(Container parent, String name)
Flips to the component that was added to this layout with the specified name, using addLayoutComponent.
20String toString()
Returns a string representation of the state of this card layout.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

CardLayout Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingLayoutDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showCardLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   
   private void showCardLayoutDemo(){
      headerLabel.setText("Layout in action: CardLayout");      

      final JPanel panel = new JPanel();
      panel.setBackground(Color.CYAN);
      panel.setSize(300,300);

      CardLayout layout = new CardLayout();
      layout.setHgap(10);
      layout.setVgap(10);
      panel.setLayout(layout);        

      JPanel buttonPanel = new JPanel(new FlowLayout());

      buttonPanel.add(new JButton("OK"));
      buttonPanel.add(new JButton("Cancel"));    

      JPanel textBoxPanel = new JPanel(new FlowLayout());

      textBoxPanel.add(new JLabel("Name:"));
      textBoxPanel.add(new JTextField(20));

      panel.add("Button", buttonPanel);
      panel.add("Text", textBoxPanel);
      
   final DefaultComboBoxModel panelName = new DefaultComboBoxModel();

      panelName.addElement("Button");
      panelName.addElement("Text");
        
   final JComboBox listCombo = new JComboBox(panelName);    
      listCombo.setSelectedIndex(0);

      JScrollPane listComboScrollPane = new JScrollPane(listCombo);    

      JButton showButton = new JButton("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) { 
            String data = "";
            if (listCombo.getSelectedIndex() != -1) {  
               CardLayout cardLayout = (CardLayout)(panel.getLayout());
               cardLayout.show(panel, 
               (String)listCombo.getItemAt(listCombo.getSelectedIndex()));                
            }              
            statusLabel.setText(data);
         }
      }); 
   
      controlPanel.add(listComboScrollPane);
      controlPanel.add(showButton);
   controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo
Verify the following output
SWING  CardLayout

SWING FlowLayout Class

Introduction

The class FlowLayout components in a left-to-right flow.

Class declaration

Following is the declaration for java.awt.FlowLayout class:
public class FlowLayout
   extends Object
      implements LayoutManager, Serializable

Field

Following are the fields for java.awt.BorderLayout class:
  • static int CENTER -- This value indicates that each row of components should be centered.
  • static int LEADING -- This value indicates that each row of components should be justified to the leading edge of the container's orientation, for example, to the left in left-to-right orientations.
  • static int LEFT -- This value indicates that each row of components should be left-justified.
  • static int RIGHT -- This value indicates that each row of components should be right-justified.
  • static int TRAILING -- This value indicates that each row of components should be justified to the trailing edge of the container's orientation, for example, to the right in left-to-right orientations.

Class constructors

S.N.Constructor & Description
1FlowLayout()
Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap.
2FlowLayout(int align)
Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap.
3FlowLayout(int align, int hgap, int vgap)
Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.

Class methods

S.N.Method & Description
1void addLayoutComponent(String name, Component comp)
Adds the specified component to the layout.
2int getAlignment()
Gets the alignment for this layout.
3int getHgap()
Gets the horizontal gap between components.
4int getVgap()
Gets the vertical gap between components.
5void layoutContainer(Container target)
Lays out the container.
6Dimension minimumLayoutSize(Container target)
Returns the minimum dimensions needed to layout the visible components contained in the specified target container.
7Dimension preferredLayoutSize(Container target)
Returns the preferred dimensions for this layout given the visible components in the specified target container.
8void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
9void setAlignment(int align)
Sets the alignment for this layout.
10void setHgap(int hgap)
Sets the horizontal gap between components.
11void setVgap(int vgap)
Sets the vertical gap between components.
12String toString()
Returns a string representation of this FlowLayout object and its values.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

FlowLayout Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingLayoutDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showFlowLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showFlowLayoutDemo(){
      headerLabel.setText("Layout in action: FlowLayout");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(200,200);
      FlowLayout layout = new FlowLayout();
      layout.setHgap(10);              
      layout.setVgap(10);
      panel.setLayout(layout);        
      panel.add(new JButton("OK"));
      panel.add(new JButton("Cancel"));       

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo
Verify the following output
SWING  FlowLayout

SWING GridLayout Class

Introduction

The class GridLayout arranges components in a rectangular grid.

Class declaration

Following is the declaration for java.awt.GridLayout class:
public class GridLayout
   extends Object
      implements LayoutManager, Serializable

Class constructors

S.N.Constructor & Description
1GridLayout()
Creates a grid layout with a default of one column per component, in a single row.
2GridLayout(int rows, int cols)
Creates a grid layout with the specified number of rows and columns.
3GridLayout(int rows, int cols, int hgap, int vgap)
Creates a grid layout with the specified number of rows and columns.

Class methods

S.N.Method & Description
1void addLayoutComponent(String name, Component comp)
Adds the specified component with the specified name to the layout.
2int getColumns()
Gets the number of columns in this layout.
3int getHgap()
Gets the horizontal gap between components.
4int getRows()
Gets the number of rows in this layout.
5int getVgap()
Gets the vertical gap between components.
6void layoutContainer(Container parent)
Lays out the specified container using this layout.
7Dimension minimumLayoutSize(Container parent)
Determines the minimum size of the container argument using this grid layout.
8Dimension preferredLayoutSize(Container parent)
Determines the preferred size of the container argument using this grid layout.
9void removeLayoutComponent(Component comp)
Removes the specified component from the layout.
10void setColumns(int cols)
Sets the number of columns in this layout to the specified value.
11void setHgap(int hgap)
Sets the horizontal gap between components to the specified value.
12void setRows(int rows)
Sets the number of rows in this layout to the specified value.
13void setVgap(int vgap)
Sets the vertical gap between components to the specified value.
14String toString()
Returns the string representation of this grid layout's values.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

GridLayout Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingLayoutDemo.java
package com.tutorialspoint.gui;

import javax.swing.*;

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

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showGridLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   
   private void showGridLayoutDemo(){
      headerLabel.setText("Layout in action: GridLayout");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      GridLayout layout = new GridLayout(0,3);
      layout.setHgap(10);
      layout.setVgap(10);
      
      panel.setLayout(layout);        
      panel.add(new JButton("Button 1"));
      panel.add(new JButton("Button 2")); 
      panel.add(new JButton("Button 3")); 
      panel.add(new JButton("Button 4")); 
      panel.add(new JButton("Button 5")); 
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo
Verify the following output
SWING  GridLayout

SWING GridBagLayout Class

Introduction

The class GridBagLayout arranges components in a horizontal and vertical manner.

Class declaration

Following is the declaration for java.awt.GridBagLayout class:
public class GridBagLayout
   extends Object
      implements LayoutManager2, Serializable

Field

Following are the fields for java.awt.GridBagLayout class:
  • static int DEFAULT_SIZE --Indicates the size from the component or gap should be used for a particular range value.
  • static int PREFERRED_SIZE --Indicates the preferred size from the component or gap should be used for a particular range value.

Class constructors

S.N.Constructor & Description
1GridBagLayout()
Creates a grid bag layout manager.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to the layout, using the specified constraints object.
2void addLayoutComponent(String name, Component comp)
Adds the specified component with the specified name to the layout.
3protected void adjustForGravity(GridBagConstraints constraints, Rectangle r)
Adjusts the x, y, width, and height fields to the correct values depending on the constraint geometry and pads.
4protected void AdjustForGravity(GridBagConstraints constraints, Rectangle r)
This method is obsolete and supplied for backwards compatability only; new code should call adjustForGravity instead.
5protected void arrangeGrid(Container parent)
Lays out the grid.
6protected void ArrangeGrid(Container parent)
This method is obsolete and supplied for backwards compatability only; new code should call arrangeGrid instead.
7GridBagConstraints getConstraints(Component comp)
Gets the constraints for the specified component.
8float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
9float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
10int[][] getLayoutDimensions()
Determines column widths and row heights for the layout grid.
11protected java.awt.GridBagLayoutInfo getLayoutInfo(Container parent, int sizeflag)
Fills in an instance of GridBagLayoutInfo for the current set of managed children.
12protected java.awt.GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag)
This method is obsolete and supplied for backwards compatability only; new code should call getLayoutInfo instead.
13Point getLayoutOrigin()
Determines the origin of the layout area, in the graphics coordinate space of the target container.
14double[][] getLayoutWeights()
Determines the weights of the layout grid's columns and rows.
15protected Dimension getMinSize(Container parent, java.awt.GridBagLayoutInfo info)
Figures out the minimum size of the master based on the information from getLayoutInfo().
16protected Dimension GetMinSize(Container parent, java.awt.GridBagLayoutInfo info)
This method is obsolete and supplied for backwards compatability only; new code should call getMinSize instead.
17void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
18void layoutContainer(Container parent)
Lays out the specified container using this grid bag layout.
19Point location(int x, int y)
Determines which cell in the layout grid contains the point specified by (x, y).
20protected GridBagConstraints lookupConstraints(Component comp)
Retrieves the constraints for the specified component.
21Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the specified target container.
22Dimension minimumLayoutSize(Container parent)
Determines the minimum size of the parent container using this grid bag layout.
23Dimension preferredLayoutSize(Container parent)
Determines the preferred size of the parent container using this grid bag layout.
24void removeLayoutComponent(Component comp)
Removes the specified component from this layout.
25void setConstraints(Component comp, GridBagConstraints constraints)
Sets the constraints for the specified component in this layout.
26String toString()
Returns a string representation of this grid bag layout's values.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

GridBagLayout Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingLayoutDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showGridBagLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showGridBagLayoutDemo(){
      headerLabel.setText("Layout in action: GridBagLayout");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.darkGray);
      panel.setSize(300,300);
      GridBagLayout layout = new GridBagLayout();

      panel.setLayout(layout);        
      GridBagConstraints gbc = new GridBagConstraints();

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridx = 0;
      gbc.gridy = 0;
      panel.add(new JButton("Button 1"),gbc);

      gbc.gridx = 1;
      gbc.gridy = 0;
      panel.add(new JButton("Button 2"),gbc); 

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.ipady = 20;   
      gbc.gridx = 0;
      gbc.gridy = 1;
      panel.add(new JButton("Button 3"),gbc); 

      gbc.gridx = 1;
      gbc.gridy = 1;       
      panel.add(new JButton("Button 4"),gbc);  

      gbc.gridx = 0;
      gbc.gridy = 2;      
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridwidth = 2;
      panel.add(new JButton("Button 5"),gbc);  

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo
Verify the following output
SWING  GridBagLayout

SWING GroupLayout Class

Introduction

The class GroupLayout hierarchically groups components in order to position them in a Container .

Class declaration

Following is the declaration for javax.swing.GroupLayout class:
public class GroupLayout
   extends Object
      implements LayoutManager2

Field

Following are the fields for javax.swing.GroupLayout class:
  • static int DEFAULT_SIZE -- Indicates the size from the component or gap should be used for a particular range value.
  • static int PREFERRED_SIZE -- Indicates the preferred size from the component or gap should be used for a particular range value.

Class constructors

S.N.Constructor & Description
1GroupLayout(Container host)
Creates a GroupLayout for the specified Container.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component component, Object constraints)
Notification that a Component has been added to the parent container.
2void addLayoutComponent(String name, Component component)
Notification that a Component has been added to the parent container.
3GroupLayout.ParallelGroup createBaselineGroup(boolean resizable, boolean anchorBaselineToTop)
Creates and returns a ParallelGroup that aligns it's elements along the baseline.
4GroupLayout.ParallelGroup createParallelGroup()
Creates and returns a ParallelGroup with an alignment of Alignment.LEADING.
5GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment alignment)
Creates and returns a ParallelGroup with the specified alignment.
6GroupLayout.ParallelGroup createParallelGroup(GroupLayout.Alignment alignment, boolean resizable)
Creates and returns a ParallelGroup with the specified alignment and resize behavior.
7GroupLayout.SequentialGroup createSequentialGroup()
Creates and returns a SequentialGroup.
8boolean getAutoCreateContainerGaps()
Returns true if gaps between the container and components that border the container are automatically created.
9boolean getAutoCreateGaps()
Returns true if gaps between components are automatically created.
10boolean getHonorsVisibility()
Returns whether component visiblity is considered when sizing and positioning components.
11float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
12float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
13LayoutStyle getLayoutStyle()
Returns the LayoutStyle used for calculating the preferred gap between components.
14void invalidateLayout(Container parent)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
15void layoutContainer(Container parent)
Lays out the specified container.
16void linkSize(Component... components)
Forces the specified components to have the same size regardless of their preferred, minimum or maximum sizes.
17void linkSize(int axis, Component... components)
Forces the specified components to have the same size along the specified axis regardless of their preferred, minimum or maximum sizes.
18Dimension maximumLayoutSize(Container parent)
Returns the maximum size for the specified container.
19Dimension minimumLayoutSize(Container parent)
Returns the minimum size for the specified container.
20Dimension preferredLayoutSize(Container parent)
Returns the preferred size for the specified container.
21void removeLayoutComponent(Component component)
Notification that a Component has been removed from the parent container.
22void replace(Component existingComponent, Component newComponent)
Replaces an existing component with a new one.
23void setAutoCreateContainerGaps(boolean autoCreateContainerPadding)
Sets whether a gap between the container and components that touch the border of the container should automatically be created.
24void setAutoCreateGaps(boolean autoCreatePadding)
Sets whether a gap between components should automatically be created.
25void setHonorsVisibility(boolean honorsVisibility)
Sets whether component visiblity is considered when sizing and positioning components.
26void setHonorsVisibility(Component component, Boolean honorsVisibility)
Sets whether the component's visiblity is considered for sizing and positioning.
27void setHorizontalGroup(GroupLayout.Group group)
Sets the Group that positions and sizes components along the horizontal axis.
28void setLayoutStyle(LayoutStyle layoutStyle)
Sets the LayoutStyle used to calculate the preferred gaps between components.
29void setVerticalGroup(GroupLayout.Group group)
Sets the Group that positions and sizes components along the vertical axis.
30String toString()
Returns a string representation of this GroupLayout.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

GroupLayout Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingLayoutDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showGroupLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showGroupLayoutDemo(){
      headerLabel.setText("Layout in action: GroupLayout");      

      JPanel panel = new JPanel();
      // panel.setBackground(Color.darkGray);
      panel.setSize(200,200);
      GroupLayout layout = new GroupLayout(panel);
      layout.setAutoCreateGaps(true);
      layout.setAutoCreateContainerGaps(true);
      JButton btn1 = new JButton("Button 1");
      JButton btn2 = new JButton("Button 2");
      JButton btn3 = new JButton("Button 3");

      layout.setHorizontalGroup(layout.createSequentialGroup()
         .addComponent(btn1)
         .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(
               GroupLayout.Alignment.LEADING)
               .addComponent(btn2)
               .addComponent(btn3)       
            )
         )    
      );


      layout.setVerticalGroup(layout.createSequentialGroup()
         .addComponent(btn1)
         .addComponent(btn2)
         .addComponent(btn3)                                    
      );
      panel.setLayout(layout);        
      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo
Verify the following output
SWING GroupLayout

SWING SpringLayout Class

Introduction

The class SpringLayout positions the children of its associated container according to a set of constraints.

Class declaration

Following is the declaration for javax.swing.SpringLayout class:
public class SpringLayout
   extends Object
      implements LayoutManager2

Field

Following are the fields for javax.swing.SpringLayout class:
  • static String BASELINE --Specifies the baseline of a component.
  • static String EAST --Specifies the right edge of a component's bounding rectangle.
  • static String HEIGHT --Specifies the height of a component's bounding rectangle.
  • static String HORIZONTAL_CENTER --Specifies the horizontal center of a component's bounding rectangle.
  • static String NORTH --Specifies the top edge of a component's bounding rectangle.
  • static String SOUTH --Specifies the bottom edge of a component's bounding rectangle.
  • static String VERTICAL_CENTER --Specifies the vertical center of a component's bounding rectangle.
  • static String WEST --Specifies the left edge of a component's bounding rectangle.
  • static String WIDTH --Specifies the width of a component's bounding rectangle.

Class constructors

S.N.Constructor & Description
1SpringLayout()
Creates a new SpringLayout.

Class methods

S.N.Method & Description
1void addLayoutComponent(Component component, Object constraints)
If constraints is an instance of SpringLayout.Constraints, associates the constraints with the specified component.
2void addLayoutComponent(String name, Component c)
Has no effect, since this layout manager does not use a per-component string.
3Spring getConstraint(String edgeName, Component c)
Returns the spring controlling the distance between the specified edge of the component and the top or left edge of its parent.
4SpringLayout.Constraints getConstraints(Component c)
Returns the constraints for the specified component.
5float getLayoutAlignmentX(Container p)
Returns 0.5f (centered).
6float getLayoutAlignmentY(Container p)
Returns 0.5f (centered).
7void invalidateLayout(Container p)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
8void layoutContainer(Container parent)
Lays out the specified container.
9Dimension maximumLayoutSize(Container parent)
Calculates the maximum size dimensions for the specified container, given the components it contains.
10Dimension minimumLayoutSize(Container parent)
Calculates the minimum size dimensions for the specified container, given the components it contains.
11Dimension preferredLayoutSize(Container parent)
Calculates the preferred size dimensions for the specified container, given the components it contains.
12void putConstraint(String e1, Component c1, int pad, String e2, Component c2)
Links edge e1 of component c1 to edge e2 of component c2, with a fixed distance between the edges.
13void putConstraint(String e1, Component c1, Spring s, String e2, Component c2)
Links edge e1 of component c1 to edge e2 of component c2.
14void removeLayoutComponent(Component c)
Removes the constraints associated with the specified component.

Methods inherited

This class inherits methods from the following classes:
  • java.lang.Object

SpringLayout Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingLayoutDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingLayoutDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();  
      swingLayoutDemo.showSpringLayoutDemo();       
   }
      
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
         System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showSpringLayoutDemo(){

      headerLabel.setText("Layout in action: SpringLayout");   
      SpringLayout layout = new SpringLayout();

      JPanel panel = new JPanel();
      panel.setLayout(layout);
      JLabel label = new JLabel("Enter Name: ");
      JTextField textField = new JTextField("", 15);
      panel.add(label);
      panel.add(textField);

      layout.putConstraint(SpringLayout.WEST, label,5,
         SpringLayout.WEST, controlPanel);
      layout.putConstraint(SpringLayout.NORTH, label,5,
         SpringLayout.NORTH, controlPanel);
      layout.putConstraint(SpringLayout.WEST, textField,5,
         SpringLayout.EAST, label);
      layout.putConstraint(SpringLayout.NORTH, textField,5,
         SpringLayout.NORTH, controlPanel);
      layout.putConstraint(SpringLayout.EAST, panel,5,
         SpringLayout.EAST, textField);
      layout.putConstraint(SpringLayout.SOUTH, panel,5,
         SpringLayout.SOUTH, textField);
      controlPanel.add(panel);
      mainFrame.setVisible(true);  
   } 
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo
Verify the following output
SWING SpringLayout

SWING Menu Classes

As we know that every top-level window has a menu bar associated with it. This menu bar consist of various menu choices available to the end user. Further each choice contains list of options which is called drop down menus. Menu and MenuItem controls are subclass of MenuComponent class.

Menu Hiearchy

Swing Menu Hiearchy

SWING JMenuBar Class

Introduction

The JMenuBar class provides an implementation of a menu bar.

Class declaration

Following is the declaration for javax.swing.JMenuBar class:
public class JMenuBar
   extends JComponent
      implements Accessible, MenuElement

Class constructors

S.N.Constructor & Description
1JMenuBar()
Creates a new menu bar.

Class methods

JMenu add(JMenu c)
Appends the specified menu to the end of the menu bar.
S.N.Method & Description
1void addNotify()
Overrides JComponent.addNotify to register this menu bar with the current keyboard manager.
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JMenuBar.
2Component getComponent()
Implemented to be a MenuElement.
3Component getComponentAtIndex(int i)
Deprecated. replaced by getComponent(int i)
4int getComponentIndex(Component c)
Returns the index of the specified component.
5JMenu getHelpMenu()
Gets the help menu for the menu bar.
6Insets getMargin()
Returns the margin between the menubar's border and its menus.
7JMenu getMenu(int index)
Returns the menu at the specified position in the menu bar.
8int getMenuCount()
Returns the number of items in the menu bar.
9SingleSelectionModel getSelectionModel()
Returns the model object that handles single selections.
10MenuElement[] getSubElements()
Implemented to be a MenuElement -- returns the menus in this menu bar.
11MenuBarUI getUI()
Returns the menubar's current UI.
12String getUIClassID()
Returns the name of the L&F class that renders this component.
13boolean isBorderPainted()
Returns true if the menu bars border should be painted.
14boolean isSelected()
Returns true if the menu bar currently has a component selected.
15void menuSelectionChanged(boolean isIncluded)
Implemented to be a MenuElement -- does nothing.
16protected void paintBorder(Graphics g)
Paints the menubar's border if BorderPainted property is true.
17protected String paramString()
Returns a string representation of this JMenuBar.
18protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed)
Subclassed to check all the child menus.
19void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)
Implemented to be a MenuElement -- does nothing.
20void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)
Implemented to be a MenuElement -- does nothing.
21void removeNotify()
Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager.
22void setBorderPainted(boolean b)
Sets whether the border should be painted.
23void setHelpMenu(JMenu menu)
Sets the help menu that appears when the user selects the "help" option in the menu bar.
24void setMargin(Insets m)
Sets the margin between the menubar's border and its menus.
25void setSelected(Component sel)
Sets the currently selected component, producing a a change to the selection model.
26void setSelectionModel(SingleSelectionModel model)
Sets the model object to handle single selections.
27void setUI(MenuBarUI ui)
Sets the L&F object that renders this component.
28void updateUI()
Resets the UI property with a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

JMenuBar Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo
Verify the following output
SWING JMenuBar

SWING JMenuItem Class

Introduction

The JMenuItem class represents the actual item in a menu. All items in a menu should derive from class JMenuItem, or one of its subclasses. By default, it embodies a simple labeled menu item.

Class declaration

Following is the declaration for javax.swing.JMenuItem class:
public class JMenuItem
   extends AbstractButton
      implements Accessible, MenuElement

Class constructors

S.N.Constructor & Description
1JMenuItem()
Creates a JMenuItem with no set text or icon.
2JMenuItem(Action a)
Creates a menu item whose properties are taken from the specified Action.
3JMenuItem(Icon icon)
Creates a JMenuItem with the specified icon.
4JMenuItem(String text)
Creates a JMenuItem with the specified text.
5JMenuItem(String text, Icon icon)
Creates a JMenuItem with the specified text and icon.
6JMenuItem(String text, int mnemonic)
Creates a JMenuItem with the specified text and keyboard mnemonic.

Class methods

S.N.Method & Description
1protected void actionPropertyChanged(Action action, String propertyName)
Updates the button's state in response to property changes in the associated action.
2void addMenuDragMouseListener(MenuDragMouseListener l)
Adds a MenuDragMouseListener to the menu item.
3void addMenuKeyListener(MenuKeyListener l)
Adds a MenuKeyListener to the menu item.
4protected void configurePropertiesFromAction(Action a)
Sets the properties on this button to match those in the specified Action.
5protected void fireMenuDragMouseDragged(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.
6protected void fireMenuDragMouseEntered(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.
7protected void fireMenuDragMouseExited(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.
8protected void fireMenuDragMouseReleased(MenuDragMouseEvent event)
Notifies all listeners that have registered interest for notification on this event type.
9protected void fireMenuKeyPressed(MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this event type.
10protected void fireMenuKeyReleased(MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this event type.
11protected void fireMenuKeyTyped(MenuKeyEvent event)
Notifies all listeners that have registered interest for notification on this event type.
12KeyStroke getAccelerator()
Returns the KeyStroke which serves as an accelerator for the menu item.
13AccessibleContext getAccessibleContext()
Returns the AccessibleContext associated with this JMenuItem.
14Component getComponent()
Returns the java.awt.Component used to paint this object.
15MenuDragMouseListener[] getMenuDragMouseListeners()
Returns an array of all the MenuDragMouseListeners added to this JMenuItem with addMenuDragMouseListener().
16MenuKeyListener[] getMenuKeyListeners()
Returns an array of all the MenuKeyListeners added to this JMenuItem with addMenuKeyListener().
17MenuElement[] getSubElements()
This method returns an array containing the sub-menu components for this menu component.
18String getUIClassID()
Returns the suffix used to construct the name of the L&F class used to render this component.
19protected void init(String text, Icon icon)
Initializes the menu item with the specified text and icon.
20boolean isArmed()
Returns whether the menu item is "armed".
21void menuSelectionChanged(boolean isIncluded)
Called by the MenuSelectionManager when the MenuElement is selected or unselected.
22protected String paramString()
Returns a string representation of this JMenuItem.
23void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)
Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager's API.
24void processMenuDragMouseEvent(MenuDragMouseEvent e)
Handles mouse drag in a menu.
25void processMenuKeyEvent(MenuKeyEvent e)
Handles a keystroke in a menu.
26void processMouseEvent(MouseEvent e, MenuElement[] path, MenuSelectionManager manager)
Processes a mouse event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using the MenuSelectionManager's API.
27void removeMenuDragMouseListener(MenuDragMouseListener l)
Removes a MenuDragMouseListener from the menu item.
28void removeMenuKeyListener(MenuKeyListener l)
Removes a MenuKeyListener from the menu item.
29void setAccelerator(KeyStroke keyStroke)
Sets the key combination which invokes the menu item's action listeners without navigating the menu hierarchy.
30void setArmed(boolean b)
Identifies the menu item as "armed".
31void setEnabled(boolean b)
Enables or disables the menu item.
32void setModel(ButtonModel newModel)
Sets the model that this button represents.
33void setUI(MenuItemUI ui)
Sets the look and feel object that renders this component.
34void updateUI()
Resets the UI property with a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:
  • javax.swing.JAbstractButton
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

JMenuItem Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo
Verify the following output. (Click on File Menu. Select any menu item.)
SWING JMenuItem

SWING JMenu Class

Introduction

The Menu class represents pull-down menu component which is deployed from a menu bar.

Class declaration

Following is the declaration for javax.swing.JMenu class:
public class JMenu
   extends JMenuItem
      implements Accessible, MenuElement

Field

Following are the fields for java.awt.Component class:
  • protected JMenu.WinListener popupListener -- The window-closing listener for the popup.

Class constructors

S.N.Constructor & Description
1JMenu()
Constructs a new JMenu with no text.
2JMenu(Action a)
Constructs a menu whose properties are taken from the Action supplied.
3JMenu(String s)
Constructs a new JMenu with the supplied string as its text.
4JMenu(String s, boolean b)
Constructs a new JMenu with the supplied string as its text and specified as a tear-off menu or not.

Class methods

S.N.Method & Description
1JMenuItem add(Action a)
Creates a new menu item attached to the specified Action object and appends it to the end of this menu.
2Component add(Component c)
Appends a component to the end of this menu.
3Component add(Component c, int index)
Adds the specified component to this container at the given position.
4JMenuItem add(JMenuItem menuItem)
Appends a menu item to the end of this menu.
5JMenuItem add(String s)
Creates a new menu item with the specified text and appends it to the end of this menu.
6void addMenuListener(MenuListener l) Adds a listener for menu events.
7void addSeparator()
Appends a new separator to the end of the menu.
8void applyComponentOrientation(ComponentOrientation o)
Sets the ComponentOrientation property of this menu and all components contained within it.
9protected PropertyChangeListener createActionChangeListener(JMenuItem b)
Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.
10protected JMenuItem createActionComponent(Action a)
Factory method which creates the JMenuItem for Actions added to the JMenu.
11protected JMenu.WinListener createWinListener(JPopupMenu p)
Creates a window-closing listener for the popup.
12void doClick(int pressTime)
Programmatically performs a "click".
13protected void fireMenuCanceled()
Notifies all listeners that have registered interest for notification on this event type.
14protected void fireMenuDeselected()
Notifies all listeners that have registered interest for notification on this event type.
15protected void fireMenuSelected()
Notifies all listeners that have registered interest for notification on this event type.
16AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JMenu.
17Component getComponent()
Returns the java.awt.Component used to paint this MenuElement.
18int getDelay()
Returns the suggested delay, in milliseconds, before submenus are popped up or down.
19JMenuItem getItem(int pos)
Returns the JMenuItem at the specified position.
20int getItemCount()
Returns the number of items on the menu, including separators.
21Component getMenuComponent(int n)
Returns the component at position n.
22int getMenuComponentCount()
Returns the number of components on the menu.
23Component[] getMenuComponents()
Returns an array of Components of the menu's subcomponents.
24MenuListener[] getMenuListeners()
Returns an array of all the MenuListeners added to this JMenu with addMenuListener().
25JPopupMenu getPopupMenu()
Returns the popupmenu associated with this menu.
26protected Point getPopupMenuOrigin()
Computes the origin for the JMenu's popup menu.
27MenuElement[] getSubElements()
Returns an array of MenuElements containing the submenu for this menu component.
28String getUIClassID()
Returns the name of the L&F class that renders this component.
29JMenuItem insert(Action a, int pos)
Inserts a new menu item attached to the specified Action object at a given position.
30JMenuItem insert(JMenuItem mi, int pos)
Inserts the specified JMenuitem at a given position.
31void insert(String s, int pos)
Inserts a new menu item with the specified text at a given position.
32void insertSeparator(int index)
Inserts a separator at the specified position.
33boolean isMenuComponent(Component c)
Returns true if the specified component exists in the submenu hierarchy.
34boolean isPopupMenuVisible()
Returns true if the menu's popup window is visible.
35boolean isSelected()
Returns true if the menu is currently selected (highlighted).
36boolean isTearOff()
Returns true if the menu can be torn off.
37boolean isTopLevelMenu()
Returns true if the menu is a 'top-level menu', that is, if it is the direct child of a menubar.
38void menuSelectionChanged(boolean isIncluded)
Messaged when the menubar selection changes to activate or deactivate this menu.
39protected String paramString()
Returns a string representation of this JMenu.
40protected void processKeyEvent(KeyEvent evt)
Processes key stroke events such as mnemonics and accelerators.
41void remove(Component c)
Removes the component c from this menu.
42void remove(int pos)
Removes the menu item at the specified index from this menu.
43void remove(JMenuItem item)
Removes the specified menu item from this menu.
44void removeAll()
Removes all menu items from this menu.
45void removeMenuListener(MenuListener l)
Removes a listener for menu events.
46void setAccelerator(KeyStroke keyStroke)
setAccelerator is not defined for JMenu.
47void setComponentOrientation(ComponentOrientation o)
Sets the language-sensitive orientation that is to be used to order the elements or text within this component.
48void setDelay(int d)
Sets the suggested delay before the menu's PopupMenu is popped up or down.
49void setMenuLocation(int x, int y)
Sets the location of the popup component.
50void setModel(ButtonModel newModel)
Sets the data model for the "menu button" -- the label that the user clicks to open or close the menu.
51void setPopupMenuVisible(boolean b)
Sets the visibility of the menu's popup.
52void setSelected(boolean b)
Sets the selection status of the menu.
53void updateUI()
Resets the UI property with a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:
  • javax.swing.JAbstractButton
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

JMenu Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo
Verify the following output. (Click on File Menu.)
SWING JMenu

SWING JCheckboxMenuItem Class

Introduction

The JCheckboxMenuItem class represents a check box which can be included in a menu. Selecting the check box in the menu changes control's state from on to off or from off to on.

Class declaration

Following is the declaration for javax.swing.JCheckBoxMenuItem class:
public class JCheckBoxMenuItem
   extends JMenuItem
      implements SwingConstants, Accessible

Class constructors

S.N.Constructor & Description
1JCheckboxMenuItem()
Creates an initially unselected check box menu item with no set text or icon.
2JCheckboxMenuItem(Action a)
Creates a menu item whose properties are taken from the Action supplied.
3JCheckboxMenuItem(Icon icon)
Creates an initially unselected check box menu item with an icon.
4JCheckboxMenuItem(String text)
Creates an initially unselected check box menu item with text.
5JCheckboxMenuItem(String text, boolean b)
Creates a check box menu item with the specified text and selection state.
6JCheckboxMenuItem(String text, Icon icon)
Creates an initially unselected check box menu item with the specified text and icon.
7JCheckboxMenuItem(String text, Icon icon, boolean b)
Creates a check box menu item with the specified text, icon, and selection state.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JCheckBoxMenuItem.
2Object[] getSelectedObjects()
Returns an array (length 1) containing the check box menu item label or null if the check box is not selected.
3boolean getState()
Returns the selected-state of the item.
4String getUIClassID()
Returns the name of the L&F class that renders this component.
5protected String paramString()
Returns a string representation of this JCheckBoxMenuItem.
6void setState(boolean b)
Sets the selected-state of the item.

Methods inherited

This class inherits methods from the following classes:
  • javax.swing.JMenuItem
  • javax.swing.JAbstractButton
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

JCheckboxMenuItem Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo
Verify the following output. (Click on File Menu. Unselect "Show About" menu item.)
SWING JCheckboxMenuItem

SWING JRadioButtonMenuItem Class

Introduction

The JRadioButtonMenuItem class represents a check box which can be included in a menu. Selecting the check box in the menu changes control's state from on to off or from off to on.

Class declaration

Following is the declaration for javax.swing.JRadioButtonMenuItem class:
public class JRadioButtonMenuItem
   extends JMenuItem
      implements Accessible

Class constructors

S.N.Constructor & Description
1JRadioButtonMenuItem()
Creates a JRadioButtonMenuItem with no set text or icon.
2JRadioButtonMenuItem(Action a)
Creates a radio button menu item whose properties are taken from the Action supplied.
3JRadioButtonMenuItem(Icon icon)
Creates a JRadioButtonMenuItem with an icon.
4JRadioButtonMenuItem(Icon icon, boolean selected)
Creates a radio button menu item with the specified image and selection state, but no text.
5JRadioButtonMenuItem(String text)
Creates a JRadioButtonMenuItem with text.
6JRadioButtonMenuItem(String text, boolean selected)
Creates a radio button menu item with the specified text and selection state.
7JRadioButtonMenuItem(String text, Icon icon)
Creates a radio button menu item with the specified text and Icon.
8JRadioButtonMenuItem(String text, Icon icon, boolean selected)
Creates a radio button menu item that has the specified text, image, and selection state.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JRadioButtonMenuItem.
2String getUIClassID()
Returns the name of the L&F class that renders this component.
3protected String paramString()
Returns a string representation of this JRadioButtonMenuItem.

Methods inherited

This class inherits methods from the following classes:
  • javax.swing.JMenuItem
  • javax.swing.JAbstractButton
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

JRadioButtonMenuItem Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showMenuDemo(){
      //create a menu bar
      final JMenuBar menuBar = new JMenuBar();

      //create menus
      JMenu fileMenu = new JMenu("File");
      JMenu editMenu = new JMenu("Edit"); 
      final JMenu aboutMenu = new JMenu("About");
      final JMenu linkMenu = new JMenu("Links");
     
      //create menu items
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      newMenuItem.setActionCommand("New");

      JMenuItem openMenuItem = new JMenuItem("Open");
      openMenuItem.setActionCommand("Open");

      JMenuItem saveMenuItem = new JMenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      JMenuItem exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      final JCheckBoxMenuItem showWindowMenu = 
         new JCheckBoxMenuItem("Show About", true);
      showWindowMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(showWindowMenu.getState()){
               menuBar.add(aboutMenu);
            }else{
               menuBar.remove(aboutMenu);
            }
         }
      });

      final JRadioButtonMenuItem showLinksMenu = 
         new JRadioButtonMenuItem("Show Links", true);
      showLinksMenu.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            if(menuBar.getMenu(3)!= null){
               menuBar.remove(linkMenu);
               mainFrame.repaint();
            }else{                   
               menuBar.add(linkMenu);
               mainFrame.repaint();
            }
         }
      });

      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(showWindowMenu);
      fileMenu.addSeparator();
      fileMenu.add(showLinksMenu);       
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);        
      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);

      //add menu to menubar
      menuBar.add(fileMenu);
      menuBar.add(editMenu);
      menuBar.add(aboutMenu);       
      menuBar.add(linkMenu);

      //add menubar to the frame
      mainFrame.setJMenuBar(menuBar);
      mainFrame.setVisible(true);     
   }

   class MenuItemListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {            
         statusLabel.setText(e.getActionCommand() 
         + " JMenuItem clicked.");
      }    
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo
Verify the following output. (Click on File Menu. Unselect "Show Link" menu item.)
SWING JRadioButtonMenuItem

SWING JPopupMenu Class

Introduction

Popup menu represents a menu which can be dynamically popped up at a specified position within a component.

Class declaration

Following is the declaration for javax.swing.JPopupMenu class:
public class JPopupMenu
   extends JComponent
      implements Accessible, MenuElement

Class constructors

S.N.Constructor & Description
1JPopupMenu()
Constructs a JPopupMenu without an "invoker".
2JPopupMenu(String label)
Constructs a JPopupMenu with the specified title.

Class methods

S.N.Method & Description
1JMenuItem add(Action a)
Appends a new menu item to the end of the menu which dispatches the specified Action object.
2JMenuItem add(JMenuItem menuItem)
Appends the specified menu item to the end of this menu.
3JMenuItem add(String s)
Creates a new menu item with the specified text and appends it to the end of this menu.
4void addMenuKeyListener(MenuKeyListener l)
Adds a MenuKeyListener to the popup menu.
5void addPopupMenuListener(PopupMenuListener l)
Adds a PopupMenu listener.
6void addSeparator()
Appends a new separator at the end of the menu.
7protected PropertyChangeListener createActionChangeListener(JMenuItem b)
Returns a properly configured PropertyChangeListener which updates the control as changes to the Action occur.
8protected JMenuItem createActionComponent(Action a)
Factory method which creates the JMenuItem for Actions added to the JPopupMenu.
9protected void firePopupMenuCanceled()
Notifies PopupMenuListeners that this popup menu is cancelled.
10protected void firePopupMenuWillBecomeInvisible()
Notifies PopupMenuListeners that this popup menu will become invisible.
11protected void firePopupMenuWillBecomeVisible()
Notifies PopupMenuListeners that this popup menu will become visible.
12AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JPopupMenu.
13Component getComponent()
Returns this JPopupMenu component.
14Component getComponentAtIndex(int i)
Deprecated. replaced by Container.getComponent(int)
15int getComponentIndex(Component c)
Returns the index of the specified component.
16static boolean getDefaultLightWeightPopupEnabled()
Gets the defaultLightWeightPopupEnabled property, which by default is true.
17Component getInvoker()
Returns the component which is the 'invoker' of this popup menu.
18String getLabel()
Returns the popup menu's label
19Insets getMargin()
Returns the margin, in pixels, between the popup menu's border and its containees.
20MenuKeyListener[] getMenuKeyListeners()
Returns an array of all the MenuKeyListeners added to this JPopupMenu with addMenuKeyListener().
21PopupMenuListener[] getPopupMenuListeners()
Returns an array of all the PopupMenuListeners added to this JMenuItem with addPopupMenuListener().
22SingleSelectionModel getSelectionModel()
Returns the model object that handles single selections.
23MenuElement[] getSubElements()
Returns an array of MenuElements containing the submenu for this menu component.
24PopupMenuUI getUI()
Returns the look and feel (L&F) object that renders this component.
25String getUIClassID()
Returns the name of the L&F class that renders this component.
26void insert(Action a, int index)
Inserts a menu item for the specified Action object at a given position.
27void insert(Component component, int index)
Inserts the specified component into the menu at a given position.
28boolean isBorderPainted()
Checks whether the border should be painted.
29boolean isLightWeightPopupEnabled()
Gets the lightWeightPopupEnabled property.
30boolean isPopupTrigger(MouseEvent e)
Returns true if the MouseEvent is considered a popup trigger by the JPopupMenu's currently installed UI.
31boolean isVisible()
Returns true if the popup menu is visible (currently being displayed).
32void menuSelectionChanged(boolean isIncluded)
Messaged when the menubar selection changes to activate or deactivate this menu.
33void pack()
Lays out the container so that it uses the minimum space needed to display its contents.
34protected void paintBorder(Graphics g)
Paints the popup menu's border if the borderPainted property is true.
35protected String paramString()
Returns a string representation of this JPopupMenu.
36protected void processFocusEvent(FocusEvent evt)
Processes focus events occurring on this component by dispatching them to any registered FocusListener objects.
37protected void processKeyEvent(KeyEvent evt)
Processes key stroke events such as mnemonics and accelerators.
38void processKeyEvent(KeyEvent e, MenuElement[] path, MenuSelectionManager manager)
Processes a key event forwarded from the MenuSelectionManager and changes the menu selection, if necessary, by using MenuSelectionManager's API.
39void processMouseEvent(MouseEvent event, MenuElement[] path, MenuSelectionManager manager)
This method is required to conform to the MenuElement interface, but it not implemented.
40void remove(int pos)
Removes the component at the specified index from this popup menu.
41void removeMenuKeyListener(MenuKeyListener l)
Removes a MenuKeyListener from the popup menu.
42void removePopupMenuListener(PopupMenuListener l)
Removes a PopupMenu listener.
43void setBorderPainted(boolean b)
Sets whether the border should be painted.
44static void setDefaultLightWeightPopupEnabled(boolean aFlag)
Sets the default value of the lightWeightPopupEnabled property.
45void setInvoker(Component invoker)
Sets the invoker of this popup menu -- the component in which the popup menu menu is to be displayed.
46void setLabel(String label)
Sets the popup menu's label.
47void setLightWeightPopupEnabled(boolean aFlag)
Sets the value of the lightWeightPopupEnabled property, which by default is true.
48void setLocation(int x, int y)
Sets the location of the upper left corner of the popup menu using x, y coordinates.
49void setPopupSize(Dimension d)
Sets the size of the Popup window using a Dimension object.
50void setPopupSize(int width, int height)
Sets the size of the Popup window to the specified width and height.
51void setSelected(Component sel)
Sets the currently selected component, This will result in a change to the selection model.
52void setSelectionModel(SingleSelectionModel model)
Sets the model object to handle single selections.
53void setUI(PopupMenuUI ui)
Sets the L&F object that renders this component.
54void setVisible(boolean b)
Sets the visibility of the popup menu.
55void show(Component invoker, int x, int y)
Displays the popup menu at the position x,y in the coordinate space of the component invoker.
56void updateUI()
Resets the UI property to a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

JPopupMenu Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingMenuDemo.java
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

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

   public SwingMenuDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingMenuDemo  swingMenuDemo = new SwingMenuDemo();     
      swingMenuDemo.showPopupMenuDemo();
   }
   
   private void prepareGUI(){
      mainFrame = new JFrame("Java SWING Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));

      headerLabel = new JLabel("",JLabel.CENTER );
      statusLabel = new JLabel("",JLabel.CENTER);        

      statusLabel.setSize(350,100);
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

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

   private void showPopupMenuDemo(){
      final JPopupMenu editMenu = new JPopupMenu("Edit"); 

      JMenuItem cutMenuItem = new JMenuItem("Cut");
      cutMenuItem.setActionCommand("Cut");

      JMenuItem copyMenuItem = new JMenuItem("Copy");
      copyMenuItem.setActionCommand("Copy");

      JMenuItem pasteMenuItem = new JMenuItem("Paste");
      pasteMenuItem.setActionCommand("Paste");

      MenuItemListener menuItemListener = new MenuItemListener();

      cutMenuItem.addActionListener(menuItemListener);
      copyMenuItem.addActionListener(menuItemListener);
      pasteMenuItem.addActionListener(menuItemListener);

      editMenu.add(cutMenuItem);
      editMenu.add(copyMenuItem);
      editMenu.add(pasteMenuItem);   

      mainFrame.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {            
            editMenu.show(mainFrame, e.getX(), e.getY());
         }               
      });
      mainFrame.add(editMenu); 
      mainFrame.setVisible(true);
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingMenuDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingMenuDemo
Verify the following output. (Click in the middle on the screen.)
SWING JPopupMenu

SWING Containers

Containers are integral part of SWING GUI components. A container provides a space where a component can be located. A Container in AWT is a component itself and it adds the capability to add component to itself. Following are noticable points to be considered.
  • Sub classes of Container are called as Container. For example JPanel, JFrame and JWindow.
  • Container can add only Component to itself.
  • A default layout is present in each container which can be overridden using setLayout method.

SWING JPanel Class

Introduction

The class JPanel is a generic lightweight container.

Class declaration

Following is the declaration for javax.swing.JPanel class:
public class JPanel
   extends JComponent
      implements Accessible

Class constructors

S.N.Constructor & Description
1JPanel()
Creates a new JPanel with a double buffer and a flow layout.
2JPanel(boolean isDoubleBuffered)
Creates a new JPanel with FlowLayout and the specified buffering strategy.
3JPanel(LayoutManager layout)
Create a new buffered JPanel with the specified layout manager.
4JPanel(LayoutManager layout, boolean isDoubleBuffered)
Creates a new JPanel with the specified layout manager and buffering strategy.

Class methods

S.N.Method & Description
1AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JPanel.
2PanelUI getUI()
Returns the look and feel (L&F) object that renders this component.
3String getUIClassID()
Returns a string that specifies the name of the L&F class that renders this component.
4protected String paramString()
Returns a string representation of this JPanel.
5void setUI(PanelUI ui)
Sets the look and feel (L&F) object that renders this component.
6void updateUI()
Resets the UI property with a value from the current look and feel.

Methods inherited

This class inherits methods from the following classes:
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

JPanel Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingContainerDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingContainerDemo(){
      prepareGUI();
   }

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

   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 TutorialsPoint SWING Tutorial."
         , JLabel.CENTER);

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

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


   private void showJPanelDemo(){
      headerLabel.setText("Container in action: JPanel");      

      JPanel panel = new JPanel();
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.add(msglabel);

      controlPanel.add(panel);        
      mainFrame.setVisible(true);      
   }   
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingContainerDemo
Verify the following output
SWING JPanel

SWING JFrame Class

Introduction

The class JFrame is an extended version of java.awt.Frame that adds support for the JFC/Swing component architecture.

Class declaration

Following is the declaration for javax.swing.JFrame class:
public class JFrame
   extends Frame
      implements WindowConstants, Accessible
         , RootPaneContainer

Field

Following are the fields for java.awt.Component class:
  • protected AccessibleContext accessibleContext --The accessible context property.
  • static int EXIT_ON_CLOSE --The exit application default window close operation.
  • protected JRootPane rootPane --The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
  • protected boolean rootPaneCheckingEnabled --If true then calls to add and setLayout will be forwarded to the contentPane.

Class constructors

S.N.Constructor & Description
1JFrame()
Constructs a new frame that is initially invisible.
2JFrame(GraphicsConfiguration gc)
Creates a Frame in the specified GraphicsConfiguration of a screen device and a blank title.
3JFrame(String title)
Creates a new, initially invisible Frame with the specified title.
4JFrame(String title, GraphicsConfiguration gc)
Creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.

Class methods

S.N.Method & Description
1protected void addImpl(Component comp, Object constraints, int index)
Adds the specified child Component.
2protected JRootPane createRootPane()
Called by the constructor methods to create the default rootPane.
3protected void frameInit()
Called by the constructors to init the JFrame properly.
4AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JFrame.
5Container getContentPane()
Returns the contentPane object for this frame.
6int getDefaultCloseOperation()
Returns the operation that occurs when the user initiates a "close" on this frame.
7Component getGlassPane()
Returns the glassPane object for this frame.
8Graphics getGraphics()
Creates a graphics context for this component.
9JMenuBar getJMenuBar()
Returns the menubar set on this frame.
10JLayeredPane getLayeredPane()
Returns the layeredPane object for this frame.
11JRootPane getRootPane()
Returns the rootPane object for this frame.
12TransferHandler getTransferHandler()
Gets the transferHandler property.
13static boolean isDefaultLookAndFeelDecorated()
Returns true if newly created JFrames should have their Window decorations provided by the current look and feel.
14protected boolean isRootPaneCheckingEnabled()
Returns whether calls to add and setLayout are forwarded to the contentPane.
15protected String paramString()
Returns a string representation of this JFrame.
16protected void processWindowEvent(WindowEvent e)
Processes window events occurring on this component.
17void remove(Component comp)
Removes the specified component from the container.
18void repaint(long time, int x, int y, int width, int height)
Repaints the specified rectangle of this component within time milliseconds.
19void setContentPane(Container contentPane)
Sets the contentPane property.
20void setDefaultCloseOperation(int operation)
Sets the operation that will happen by default when the user initiates a "close" on this frame.
21static void setDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated)
Provides a hint as to whether or not newly created JFrames should have their Window decorations (such as borders, widgets to close the window, title...) provided by the current look and feel.
22void setGlassPane(Component glassPane)
Sets the glassPane property.
23void setIconImage(Image image)
Sets the image to be displayed as the icon for this window.
24void setJMenuBar(JMenuBar menubar)
Sets the menubar for this frame.
25void setLayeredPane(JLayeredPane layeredPane)
Sets the layeredPane property.
26void setLayout(LayoutManager manager)
Sets the LayoutManager.
27protected void setRootPane(JRootPane root)
Sets the rootPane property.
28protected void setRootPaneCheckingEnabled(boolean enabled)
Sets whether calls to add and setLayout are forwarded to the contentPane.
29void setTransferHandler(TransferHandler newHandler)
Sets the transferHandler property, which is a mechanism to support transfer of data into this component.
30void update(Graphics g)
Just calls paint(g).

Methods inherited

This class inherits methods from the following classes:
  • java.awt.Frame
  • java.awt.Window
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

JFrame Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingContainerDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingContainerDemo(){
      prepareGUI();
   }

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

   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 TutorialsPoint SWING Tutorial."
         , 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);  
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingContainerDemo
Verify the following output
SWING JFrame

SWING JWindow Class

Introduction

The class JWindow is a container that can be displayed but does not have the title bar or window-management buttons.

Class declaration

Following is the declaration for javax.swing.JWindow class:
public class JWindow
   extends Window
      implements Accessible, RootPaneContainer

Field

Following are the fields for java.awt.Component class:
  • protected AccessibleContext accessibleContext --The accessible context property.
  • protected JRootPane rootPane --The JRootPane instance that manages the contentPane and optional menuBar for this frame, as well as the glassPane.
  • protected boolean rootPaneCheckingEnabled --If true then calls to add and setLayout will be forwarded to the contentPane.

Class constructors

S.N.Constructor & Description
1JWindow()
Creates a window with no specified owner.
2JWindow(Frame owner)
Creates a window with the specified owner frame.
3JWindow(GraphicsConfiguration gc)
Creates a window with the specified GraphicsConfiguration of a screen device.
4JWindow(Window owner)
Creates a window with the specified owner window.
5JWindow(Window owner, GraphicsConfiguration gc)
Creates a window with the specified owner window and GraphicsConfiguration of a screen device.

Class methods

S.N.Method & Description
1protected void addImpl(Component comp, Object constraints, int index)
Adds the specified child Component.
2protected JRootPane createRootPane()
Called by the constructor methods to create the default rootPane.
3AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JWindow.
4Container getContentPane()
Returns the Container which is the contentPane for this window.
5Component getGlassPane()
Returns the glassPane Component for this window.
6Graphics getGraphics()
Creates a graphics context for this component.
7JLayeredPane getLayeredPane()
Returns the layeredPane object for this window.
8JRootPane getRootPane()
Returns the rootPane object for this window.
9TransferHandler getTransferHandler()
Gets the transferHandler property.
10protected boolean isRootPaneCheckingEnabled()
Returns whether calls to add and setLayout are forwarded to the contentPane.
11protected String paramString()
Returns a string representation of this JWindow.
12void remove(Component comp)
Removes the specified component from the container.
13void repaint(long time, int x, int y, int width, int height)
Repaints the specified rectangle of this component within time milliseconds.
14void setContentPane(Container contentPane)
Sets the contentPane property for this window.
15void setGlassPane(Component glassPane)
Sets the glassPane property.
16void setLayeredPane(JLayeredPane layeredPane)
Sets the layeredPane property.
17void setLayout(LayoutManager manager)
Sets the LayoutManager.
18protected void setRootPane(JRootPane root)
Sets the new rootPane object for this window.
19protected void setRootPaneCheckingEnabled(boolean enabled)
Sets whether calls to add and setLayout are forwarded to the contentPane.
20void setTransferHandler(TransferHandler newHandler)
Sets the transferHandler property, which is a mechanism to support transfer of data into this component.
21void update(Graphics g)
Calls paint(g).
22protected void windowInit()
Called by the constructors to init the JWindow properly.

Methods inherited

This class inherits methods from the following classes:
  • java.awt.Window
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

JWindow Example

Create the following java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingContainerDemo.java
package com.tutorialspoint.gui;

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

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

   public SwingContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      SwingContainerDemo  swingContainerDemo = new SwingContainerDemo();  
      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 TutorialsPoint SWING Tutorial."
         , 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 TutorialsPoint SWING Tutorial.");

      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); 
      } 
   }
}
Compile the program using command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingContainerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\SWING>java com.tutorialspoint.gui.SwingContainerDemo