This is a Java program to close the frame using an anonymous class.
We have to write a program in Java such that it closes a frame on click of an exit button using an anonymous class.
For closing of frame using an anonymous class, we can have the following 2 different sets of input and output.
1. To test the opening of the frame: When the frame is opened after creation.
If the frame is created and opening, that is when the program is first executed then the expected output is "Frame Opened Successfully"
2. To test the closing of the frame: When the frame is closed.
If the frame is closed, that is on click of the "Exit" button on frame then the expected output is "Frame Closed Successfully"
1. Create a frame, an exit button and object of the class.
2. Define a constructor of the class which checks the actions on the exit button and disposes the frame if the button is clicked.
Here is source code of the Java Program to handle the keyboard events. The program is successfully compiled and tested using BlueJ on Windows 10 and javac compiler on Fedora 30.
static JFrame frame;
static JButton exit;
public void actionPerformed(ActionEvent e)
System.out.println("Frame Closed Successfully");
public static void main(String args)
//Create a frame
frame=new JFrame("Close Frame Using Anonymous Class");
//Create an exit button
//Create an object of the class
Close_Frame obj=new Close_Frame();
System.out.println("Frame Opened Successfully");
1. Create a frame with background color & specific size. frame.setBackground(Color.white); is used to create the frame background color as white. frame.setSize(500,500); is used to set the width and height of the frame.
2. Create an exit button with setBounds(int x, int y, int width, int height), where ‘x’ & ‘y’ is used to set the position of top-left corner. ‘int width’ & ‘int height’ is used to set the width and height of the exit button.
3. Here the values of set bounds are setBounds(220,235,60,30), where ‘220’ & ‘235’ is used to set the position of button from top and left side of the frame. ’60’ & ’30’ is used to set the width and height of the exit button.
4. Create an object of the class with a name Close_Frame. When the object is created, the constructor is called and it checks the event of the button.
5. When the exit button is clicked, the constructor closes the frame and displays suitable message.
Here’s the run time test cases for closing of frame using an anonymous class.
Sanfoundry Global Education & Learning Series – Java Programs.