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 function
public static void main(String args[])
{
//Create a frame
frame = new JFrame("Open a File");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
//Create a label
label = new JLabel();
frame.add(label);
//Create an object
Open_File obj = new Open_File();
//Create a Menu
JMenu menu = new JMenu("File");
//Create a Menu Item
JMenuItem open = new JMenuItem("Open");
open.addActionListener(obj);
menu.add(open);
//Create a menu bar
JMenuBar mb=new JMenuBar();
mb.add(menu);
frame.setJMenuBar(mb);
//Display the frame
frame.setVisible(true);
}
//Function to create a file chooser and display the path
public void actionPerformed(ActionEvent e)
{
//Create a file chooser
JFileChooser 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.
- Practice BCA MCQs
- Practice Information Technology MCQs
- Check Java Books
- Practice Programming MCQs
- Apply for Computer Science Internship