This is a Java Program to Create a Menu and Handle the File Open Event for the User
We have to write a program in Java such that it creates a frame with a menu item to handle the File Open event.
By File Open event it means that the user shall be able to browse the system and select a file. The file path of the selected file will be displayed in the frame.
For handling the File Open event, we can have the following set of input and output.
To display the file selected:
When any file item is selected from the file browser window, it is expected that the complete file path is displayed in the frame.
1. Create a Menu with the Open menu item.
2. When the user clicks on Open, a file browser window is opened.
3. The path of file selected is displayed in the frame.
Here is source code of the Java Program to handle the file open event. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/* Java Program to handle the File Open Event*/import javax.swing.*;
import javax.swing.filechooser.*;
import java.awt.*;
import java.awt.event.*;
class Open_File implements ActionListener
{static JFrame frame;
static JLabel label;
//Driver functionpublic static void main(String args[])
{//Create a frameframe = new JFrame("Open a File");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
//Create a labellabel = new JLabel();
frame.add(label);
//Create an objectOpen_File obj = new Open_File();
//Create a MenuJMenu menu = new JMenu("File");
//Create a Menu ItemJMenuItem open = new JMenuItem("Open");
open.addActionListener(obj);
menu.add(open);
//Create a menu barJMenuBar mb=new JMenuBar();
mb.add(menu);
frame.setJMenuBar(mb);
//Display the frameframe.setVisible(true);
}//Function to create a file chooser and display the pathpublic void actionPerformed(ActionEvent e)
{//Create a file chooserJFileChooser file = new JFileChooser();
file.showOpenDialog(null);
label.setText("File : "+file.getSelectedFile());
}}
1. To create a file chooser use the JFileChooser class.
2. To view the file chooser, use showOpenDialog method.
3. Display the complete path of file.
Here’s the run time test case to handle the file open event.
Test case – To view the path of the file.

Sanfoundry Global Education & Learning Series – Java Programs.
- Apply for Computer Science Internship
- Check Programming Books
- Check Java Books
- Apply for Java Internship
- Practice BCA MCQs