0% found this document useful (0 votes)
174 views9 pages

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)
174 views9 pages

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

Choosepagelanguage

BrazilianPortuguese
Japanese
Russian
SimplifiedChinese

NetBeansIDE
NetBeansPlatform
Enterprise
Plugins
Docs&Support
Community
Search

HOME/Docs&Support

AddingaFileChoosertoaJavaApplication
ContributedbyPetrDvorak(Dec2009),maintainedbyAlyonaStashkova
ThistutorialshowshowtoaddafilechoosertoaJavaapplicationusingthe
[Link],butusingtheNetBeans
[Link],youwill
[Link].
Youcandownloadtheresultingprojectwithafilechooser.
Contents

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

CreatingtheApplication
FirstyoucreateanewJavaApplication:

[Link],chooseFile>[Link]
[Link].
[Link],typeJFileChooserDemoandspecifytheprojectlocation.
[Link].

[Link].

CreatingtheApplicationForm
Inthissection,youcreateaJFramecontainerandaddafewcomponentstoit.
TocreatetheJFrameform:
[Link]>[Link]
[Link].
[Link],typeJFileChooserDemo.
[Link],[Link].

[Link].
[Link],enterDemoapplicationfortheTitlepropertyandpressEnterto
confirm.
ToaddcomponentstotheJFrameform:
[Link],opentheSwingMenuscategory,selecttheMenuBarcomponentanddrag
ittothelefttopcorneroftheJFrame.
Note:IfyoudonotseethePalette,selectWindow>Palettefromthemainmenu.

[Link]
menu.
[Link],inthe
SwingMenuscategoryinthePalette,selectanewMenuItem(JMenuItem1),dragitto
theMenuBar,anddropittotheFileitemoftheMenuBar.

Note:MakesuretheMenuBarisselectedbeforedragginganotherMenuItemtherein
ordertohavethelatteraddedtotheMenuBar.
4.RightclickthejMenuItem1intheDesignviewandchooseChangeVariableNamefrom
[Link].
[Link]
[Link].
[Link]
Events>Action>[Link]
automaticallyswitchestotheSourceviewandaneweventhandlermethodnamed
OpenActionPerformed()[Link]:

[Link],switchback
intotheDesignmode,intheSwingMenuscategoryinthePalette,selectaMenuItem
(JMenuItem1)[Link]
highlightingthatindicateswheretheJMenuItem1isgoingtobeplaced.

8.RightclickjMenuItem1intheDesignviewandchooseChangeVariableNamefromthe
[Link].
[Link]
[Link].
[Link]
Events>Action>[Link]
automaticallyswitchestotheSourceviewandaneweventhandlermethodisgenerated
whichisnamedExitActionPerformed().TheExitActionPerformednodeappearsinthe
NavigatorwindowbelowtheOpenActionPerformed()node.
JavaProgramming
[Link],youincludethefollowingsourceintothe
Language
ExitActionPerformed()methodbody:

Training

[Link](0);

[Link],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
[Link]
[Link]
screenshot:

SampleApplications
DemosandScreencasts

More
FAQs
Contribute
Documentation!
DocsforEarlierReleases

[Link]
Chooser.

AddingtheFileChooser
[Link]>Navigating>NavigatortoopentheNavigatorwindow,ifitisnotopen
yet.
[Link],[Link]>
SwingWindows>FileChooserfromthecontextmenu
AsanalternativetotheAddFromPalettecontextmenu,youcanalsodraganddropa
JFileChoosercomponentfromtheSwingWindowcategoryofthePalettetothewhite
[Link],butitisabitharder,becausethe

previewoftheJFileChooserisratherbigandyoumightaccidentallyinsertthewindow
intooneofthepanels,whichisnotwhatyouwant.
[Link].
[Link].

[Link]
want,addacustomfilefilter,andintegratetheFileChooserintoyourapplication.

ConfiguringtheFileChooser
ImplementingtheOpenAction
[Link],andthenedititspropertiesin
[Link],
pressEnterandclosethePropertiesdialogbox.
[Link]
FileChooserintoyourapplication,pastethefollowingcodesnippetintotheexisting
OpenActionPerformed()method.
privatevoidOpenActionPerformed([Link]){
intreturnVal=[Link](this);
if(returnVal==JFileChooser.APPROVE_OPTION){
Filefile=[Link]();
try{
//Whattodowiththefile,[Link]
[Link](newFileReader([Link]()),null);
}catch(IOExceptionex){
[Link]("problemaccessingfile"+[Link]());
}
}else{
[Link]("Fileaccesscancelledbyuser.");
}
}

Note:Removethefirstandlastlinesofthecodesnippetthatduplicatetheexistingones
inthesourcefile.
[Link],rightclickanywhereinthecodeandselectFix
ImportsorpressCtrl+Shift+[Link]
updatetheimportstatementsandclickOK.
Asyoucansee,youcalltheFileChooser'sgetSelectedFile()methodtodeterminewhichfile
theuserclicked,[Link]
intheTextArea.

ImplementingaFileFilter

NowyouaddacustomfilefilterthatmakestheFileChooserdisplayonly*.txtfiles.
[Link].
[Link],clicktheelipsis("...")buttonnexttothefileFilterproperty.
[Link],selectCustomCodefromthecombobox.

[Link]:
newMyCustomFilter()

[Link].
[Link],youwriteaninner(orouter)classMyCustomFilterthat
[Link]
ofyourclassbelowtheimportstatementstocreateaninnerclassimplementingthefilter.
[Link]{
@Override
publicbooleanaccept(Filefile){
//Allowonlydirectories,orfileswith".txt"extension
[Link]()||[Link]().endsWith(".txt");
}
@Override
publicStringgetDescription(){
//Thisdescriptionwillbedisplayedinthedialog,
//hardcoded=ugly,shouldbedoneviaI18N
return"Textdocuments(*.txt)";
}
}

Note:Tolearnhowtoimplementsmarter,switchablefilefilters,havealookatthe
addChoosableFileFiltermethod.

RunningtheApplication
[Link].
[Link]
mainclassandclickOK.

[Link],[Link]
resultshouldlooklikethis:

[Link],selectExitintheFilemenu.
HavealookatotherusefulSwingwindowsanddialogsliketheColorChooserorthe
OptionPaneintheGUIPalette.
SendFeedbackonThisTutorial

NextSteps
ImplementingJavaGUIsinDevelopingApplicationswithNetBeansIDE
BindingBeansandDatainaJavaApplicationwithNetBeansIDE
InternationalizingaGUIFormwithNetBeansIDE
JavaTutorial:HowtouseFileChoosers

SiteMap
AboutUs

Contact
Legal&Licences
Byuseofthiswebsite,youagreetotheNetBeansPoliciesandTermsofUse.2016,OracleCorporationand/orits
[Link]

You might also like