0% found this document useful (0 votes)
135 views

Adding A File Chooser To A Java Application

This document provides instructions for adding a file chooser to a Java application using NetBeans. It describes how to create a simple project with a menu bar and text area, then add a file chooser and configure it to only allow .txt files. The file contents are loaded into the text area when a file is selected.

Uploaded by

koo_by
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views

Adding A File Chooser To A Java Application

This document provides instructions for adding a file chooser to a Java application using NetBeans. It describes how to create a simple project with a menu bar and text area, then add a file chooser and configure it to only allow .txt files. The file contents are loaded into the text area when a file is selected.

Uploaded by

koo_by
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Choosepagelanguage

BrazilianPortuguese
Japanese
Russian
SimplifiedChinese

NetBeansIDE
NetBeansPlatform
Enterprise
Plugins
Docs&Support
Community
Search

HOME/Docs&Support

AddingaFileChoosertoaJavaApplication
ContributedbyPetrDvorak(Dec2009),maintainedbyAlyonaStashkova
ThistutorialshowshowtoaddafilechoosertoaJavaapplicationusingthe
javax.swing.JFileChoosercomponent.Youcouldcodeitallbyhand,butusingtheNetBeans
GUIBuilderisasmartwaythatwillsaveyouabitofwork.Aspartoftheexercise,youwill
createasmallJavaapplicationthatloadsa.txtfileintoaTextArea.
Youcandownloadtheresultingprojectwithafilechooser.
Contents

CreatingtheApplication
CreatingtheApplicationForm
AddingtheFileChooser
ConfiguringtheFileChooser
RunningtheApplication
Tocompletethistutorial,youneedthefollowingsoftwareandresources.
SoftwareorResource
VersionRequired
NetBeansIDE
Version7.0ormorerecent
JavaDevelopmentKit(JDK) Version6,7,or8

CreatingtheApplication
FirstyoucreateanewJavaApplication:

1.Fromthemainmenu,chooseFile>NewProject.ChoosetheJavacategoryandtheJava
Applicationprojecttype.ClickNext.
2.ForProjectName,typeJFileChooserDemoandspecifytheprojectlocation.
3.DeselecttheCreateMainClasscheckbox.

4.ClickFinish.

CreatingtheApplicationForm
Inthissection,youcreateaJFramecontainerandaddafewcomponentstoit.
TocreatetheJFrameform:
1.RightclicktheSourcePackagesnodeandchooseNew>Other.ChoosetheSwingGUI
FormscategoryandtheJFrameFormfiletype.ClickNext.
2.ForClassName,typeJFileChooserDemo.
3.ForPackage,typejfilechooserdemo.resources.

4.ClickFinish.
5.InthePropertieswindow,enterDemoapplicationfortheTitlepropertyandpressEnterto
confirm.
ToaddcomponentstotheJFrameform:
1.InthePalette,opentheSwingMenuscategory,selecttheMenuBarcomponentanddrag
ittothelefttopcorneroftheJFrame.
Note:IfyoudonotseethePalette,selectWindow>Palettefromthemainmenu.

2.RightclicktheEdititemoftheMenuBarcomponentandselectDeleteinthecontext
menu.
3.ToaddamenuitemthatallowstoopenFileChooserfromtherunningapplication,inthe
SwingMenuscategoryinthePalette,selectanewMenuItem(JMenuItem1),dragitto
theMenuBar,anddropittotheFileitemoftheMenuBar.

Note:MakesuretheMenuBarisselectedbeforedragginganotherMenuItemtherein
ordertohavethelatteraddedtotheMenuBar.
4.RightclickthejMenuItem1intheDesignviewandchooseChangeVariableNamefrom
thecontextmenu.RenametheitemtoOpenandclickOK.
5.MakesurethatthejMenuItem1isstillselectedintheDesignview.PresstheSpacebarto
editthetextofthecomponent.ChangethetexttoOpenandpressEntertoconfirm.
6.SpecifytheactionhandlerfortheOpenmenuitem.Rightclickthemenuitemandchoose
Events>Action>actionPerformedfromthecontextmenu.TheGUIBuilder
automaticallyswitchestotheSourceviewandaneweventhandlermethodnamed
OpenActionPerformed()isgenerated.TheNavigatorwindowshouldlookasfollows:

7.ToaddamenuitemtoexitFileChooserfromtheapplicationbeingcreated,switchback
intotheDesignmode,intheSwingMenuscategoryinthePalette,selectaMenuItem
(JMenuItem1)anddragittotheMenuBarbelowtheOpenmenuitem.Noticeorange
highlightingthatindicateswheretheJMenuItem1isgoingtobeplaced.

8.RightclickjMenuItem1intheDesignviewandchooseChangeVariableNamefromthe
contextmenu.RenametheitemtoExitandclickOK.
9.MakesurethatthejMenuItem1isstillselectedintheDesignview.PresstheSpacebarto
editthetextofthecomponent.ChangethetexttoExitandpressEntertoconfirm.
10.SpecifytheactionhandlerfortheExitmenuitem.Rightclickthemenuitemandchoose
Events>Action>actionPerformedfromthecontextmenu.TheGUIBuilder
automaticallyswitchestotheSourceviewandaneweventhandlermethodisgenerated
whichisnamedExitActionPerformed().TheExitActionPerformednodeappearsinthe
NavigatorwindowbelowtheOpenActionPerformed()node.
JavaProgramming
11.TomaketheExitmenuitemwork,youincludethefollowingsourceintothe
Language
ExitActionPerformed()methodbody:

Training

System.exit(0);

12.SwitchbackintoDesignmode.FromtheSwingControlscategoryofthePalette,draga
TextArea(JTextArea)intotheformlikeshowninthepicturebelow.

Support
OracleDevelopment
ToolsSupportOffering
forNetBeansIDE

Documentation
GeneralJava
Development
ExternalToolsand
Services
JavaGUIApplications
JavaEE&JavaWeb
Development
WebServices
Applications
NetBeansPlatform
(RCP)andModule
Development
PHPandHTML5
Applications
C/C++Applications
MobileApplications
13.ResizetheaddedcomponenttomakeroomforthetextdisplayedbytheFileChooser
later.Renamethevariabletotextarea.Theformshouldlooklikethefollowing
screenshot:

SampleApplications
DemosandScreencasts

More
FAQs
Contribute
Documentation!
DocsforEarlierReleases

YouhavesetupasimpleJavaapplicationasabaseforthistutorial.NextyouaddtheactualFile
Chooser.

AddingtheFileChooser
1.ChooseWindow>Navigating>NavigatortoopentheNavigatorwindow,ifitisnotopen
yet.
2.IntheNavigator,rightclicktheOtherComponentsnode.ChooseAddFromPalette>
SwingWindows>FileChooserfromthecontextmenu
AsanalternativetotheAddFromPalettecontextmenu,youcanalsodraganddropa
JFileChoosercomponentfromtheSwingWindowcategoryofthePalettetothewhite
areaoftheGUIbuilder.Itwillhavethesameresult,butitisabitharder,becausethe

previewoftheJFileChooserisratherbigandyoumightaccidentallyinsertthewindow
intooneofthepanels,whichisnotwhatyouwant.
3.AlookintheNavigatorconfirmsthataJFileChooserwasaddedtotheform.
4.RightclicktheJFileChoosernodeandrenamethevariabletofileChooser.

YouhaveaddedaFileChooser.NextyoutunetheFileChoosertodisplaythetitlethatyou
want,addacustomfilefilter,andintegratetheFileChooserintoyourapplication.

ConfiguringtheFileChooser
ImplementingtheOpenAction
1.ClicktoselecttheJFileChooserintheNavigatorwindow,andthenedititspropertiesin
thePropertiesdialogbox.ChangethedialogTitlepropertytoThisismyopendialog,
pressEnterandclosethePropertiesdialogbox.
2.ClicktheSourcebuttonintheGUIBuildertoswitchtotheSourcemode.Tointegratethe
FileChooserintoyourapplication,pastethefollowingcodesnippetintotheexisting
OpenActionPerformed()method.
privatevoidOpenActionPerformed(java.awt.event.ActionEventevt){
intreturnVal=fileChooser.showOpenDialog(this);
if(returnVal==JFileChooser.APPROVE_OPTION){
Filefile=fileChooser.getSelectedFile();
try{
//Whattodowiththefile,e.g.displayitinaTextArea
textarea.read(newFileReader(file.getAbsolutePath()),null);
}catch(IOExceptionex){
System.out.println("problemaccessingfile"+file.getAbsolutePath());
}
}else{
System.out.println("Fileaccesscancelledbyuser.");
}
}

Note:Removethefirstandlastlinesofthecodesnippetthatduplicatetheexistingones
inthesourcefile.
3.Iftheeditorreportserrorsinyourcode,rightclickanywhereinthecodeandselectFix
ImportsorpressCtrl+Shift+I.IntheFixAllImportsdialogboxacceptthedefaultsto
updatetheimportstatementsandclickOK.
Asyoucansee,youcalltheFileChooser'sgetSelectedFile()methodtodeterminewhichfile
theuserclicked,soyoucanworkwithit.Thisexamplereadsthefilecontentsanddisplaysthem
intheTextArea.

ImplementingaFileFilter

NowyouaddacustomfilefilterthatmakestheFileChooserdisplayonly*.txtfiles.
1.SwitchtotheDesignmodeandselectthefileChooserintheNavigatorwindow.
2.InthePropertieswindow,clicktheelipsis("...")buttonnexttothefileFilterproperty.
3.IntheFileFilterdialogbox,selectCustomCodefromthecombobox.

4.Typethefollowinginthetextfield:
newMyCustomFilter()

5.ClickOK.
6.Tomakethecustomcodework,youwriteaninner(orouter)classMyCustomFilterthat
extendstheFileFilterclass.Copyandpastethefollowingcodesnippetintothesource
ofyourclassbelowtheimportstatementstocreateaninnerclassimplementingthefilter.
classMyCustomFilterextendsjavax.swing.filechooser.FileFilter{
@Override
publicbooleanaccept(Filefile){
//Allowonlydirectories,orfileswith".txt"extension
returnfile.isDirectory()||file.getAbsolutePath().endsWith(".txt");
}
@Override
publicStringgetDescription(){
//Thisdescriptionwillbedisplayedinthedialog,
//hardcoded=ugly,shouldbedoneviaI18N
return"Textdocuments(*.txt)";
}
}

Note:Tolearnhowtoimplementsmarter,switchablefilefilters,havealookatthe
addChoosableFileFiltermethod.

RunningtheApplication
1.RightclicktheJFileChooserDemoprojectandselectRuntostartthesampleproject.
2.IntheRunProjectdialogboxselectthejfilechooserdemo.resources.JFileChooserDemo
mainclassandclickOK.

3.IntherunningDemoapplication,chooseOpenintheFilemenutotriggertheaction.The
resultshouldlooklikethis:

4.Toclosetheapplication,selectExitintheFilemenu.
HavealookatotherusefulSwingwindowsanddialogsliketheColorChooserorthe
OptionPaneintheGUIPalette.
SendFeedbackonThisTutorial

NextSteps
ImplementingJavaGUIsinDevelopingApplicationswithNetBeansIDE
BindingBeansandDatainaJavaApplicationwithNetBeansIDE
InternationalizingaGUIFormwithNetBeansIDE
JavaTutorial:HowtouseFileChoosers

SiteMap
AboutUs

Contact
Legal&Licences
Byuseofthiswebsite,youagreetotheNetBeansPoliciesandTermsofUse.2016,OracleCorporationand/orits
affiliates.Sponsoredby

You might also like