ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 43

Updated on October 16, 2019
dwachira profile image

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Lesson 43: Working with Java Open File dialog box

Welcome to Lesson 43 on Programming in Java NetBeans. Over the previous lesson, we discussed how we can implement menus in Java and how we can create shortcuts for menu options. In this lesson, we shall learn the usefulness of Java Open File dialog box and how we can implement this feature in Java NetBeans.

Using Java Open File dialog box, we can access various locations in the computer and open files with ease by way of clicking on a particular file or simply by double clicking the file. Open File dialog box in Java is implemented through File Chooser class control under Java Swing Windows.

Source

For this lesson, we’ll create a new project and a new JFrame form. We’ll add a label with title “Working with Java Menus.”

We’ll then add a Java menu with Open, Save and Exit menu options together with their respective shortcuts as we did in the previous lesson (you may need to re-visit Lesson 42) to refresh.

What we need to do is to add a File Chooser on the Open menu option so that when the user clicks on Open, the Open File dialog box will be activated to enable a particular file to be selected. Below is an example of an Open File dialog box from Microsoft Office Word 7.

Microsoft Office Word 7 - Open File Dialog box

After you have created the new JFrame form it should look as shown below when run:

The Java File Chooser Class Control Under Swing Windows

Now, we need to add the File Chooser so that we can be able to activate the Open File dialog box. While you are in design view of the form drag the File Chooser control from the Swing Windows and drop it on the white space near the form but NOT into the form. You will not see any object on the form but you can note an additional object on the Inspector window under “Other components.”

We can change the default name of the File Chooser from jFileChooser1 to fc or any other name so, right click on the default jFileChooser1 name on the Inspector window, choose Change Variable Name and from the dialog box that will appear, type fc as the new variable name.

Click OK to confirm the renaming changes and the name of File Chooser component in the Inspector Widow will change for the new name.

To display the File Chooser dialog box, we use the ShowOpenDialog() method of the File Chooser class. On the form design view, double click on the Open menu option and select Event >> Action >> actionPerformed. This will take you to the code stub of the Open menu option.

We need to include the code that will display the dialog box so type the following code in the code stub of the Open menu option.

As you can see from the above code, the ShowOpenDialog() method returns an integer value and we are storing this value in a variable called returnVal. This integer value is important to us as we can tell by a number which menu option was clicked i.e. Open, Save or Exit. You will learn how useful this integer value is shortly. Run the form now, select File >> Open and you should be able to display the Open File dialog box.

Java Open File Dialog Box

Up to this point, the File Chooser should work but not as expected. Notice that selecting any file and clicking Open does not open that file as expected. To open a file, we need to know which button was clicked by the user, is it “Open” or “Cancel” for example. We’ll use a Swing class called JFileChooser to know which button was clicked by the user. Modify and add the following code in the code stub for Open menu option.

if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {

}

The above IF statement will determine if the user clicked one of the approved options. To get the file that was selected by the user, we’ll use the getSelectedFile() method of the File Chooser class. Add the following code still in the code stub for Open menu option.

java.io.File file = fc.getSelectedFile( ); //Type as one line

In the above code, we are getting the file as an object and storing it in a variable named file. Since this file is just an object, we cannot do much with it (like opening or displaying it) unless we change the object into a string. We can change the object into a string value by using the following code.

String file_name = file.toString( );

Now, to display the file that was chosen by the user, we’ll use a JOption Pane dialog box. Add the import statement at the top of your code just before the class.

import javax.swing.JOptionPane;

The code for JOption Pane dialog box should then be placed inside the code stub for Open menu option.

JOptionPane.showMessageDialog( this, file_name);

The complete code in the code stub for Open menu option should now look as follow:

The code in the code stub for Open menu option

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fc.showOpenDialog(this);
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
    java.io.File file = fc.getSelectedFile( );
    String file_name = file.toString( );
    JOptionPane.showMessageDialog(this, file_name);
}
}

Run the form again and this time you should have the JOption Pane dialog box displaying the name of the file that was selected by the user.

As you can see, we are able to get the file selected by the user through a JOption Pane dialog box. This is very useful if we were to open the file. On the Open dialog box image above, you will notice that File of Type option is set to All Files. We can customize this so that apart from opening all files we can also filter the files to be opened by file extensions. We’ll do this in the next lesson.

<< Lesson 42 | Lesson 44 >>

Comments

    0 of 8192 characters used
    Post Comment
    • profile image

      Benson 

      8 years ago

      Great stuff, i like this!!!!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      8 years ago from Nairobi, Kenya

      Hi Iman,

      Thanks for keeping up the follow, am glad that you have benefited from this tutorial. Thanks too for the visit and comment.

    • profile image

      Iman 

      8 years ago

      Another great article, i like following this tutorial and usually on look out for new lessons. Thanks for keeping going.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)