1 Package com.soft.test;2 3 //Awt:filedialog class + FilenameFilter class can implement this function4 //Swing:jfilechooser class + FileFilter class can implement this function5 //6 //This class is used to test open files and save files in the dialog box7 8Import java.awt.*;//in order to use the layout manager9Import java.awt.Event.*;//used to handle eventsTenImport javax.swing.*;//The latest GUI components OneImport java.io.*;//for reading and writing files A - Public classFilechooser { - the PrivateJFrame frm; - PrivateJButton Open; - PrivateJButton Read; - PrivateJPanel p; + PrivateFile F; - PrivateJFileChooser FC; + Private intFlag; A at PublicFilechooser () { -frm =NewJFrame ("Java"); -Open =NewJButton ("Open"); -Read =NewJButton ("Read"); -p =NewJPanel (); -FC =NewJFileChooser (); in -Container C =Frm.getcontentpane (); toC.setlayout (NewFlowLayout ()); + - C.add (p); the p.add (open); * p.add (read); $ Panax Notoginseng //Register button Event -Open.addactionlistener (Newaction ()); theRead.addactionlistener (Newaction ()); + AFrm.setsize ( -, -); theFrm.setvisible (true); + //Set the default shutdown action - frm.setdefaultcloseoperation (jframe.exit_on_close); $ } $ - Private voidOpenFile ()//Open File - { the //set the title of the Open File dialog box -Fc.setdialogtitle ("Open File");Wuyi the //This shows the Open File dialog box - Try { WuFlag =fc.showopendialog (frm); -}Catch(headlessexception head) { About $System. out. println ("Open File Dialog error!"); - } - - //If you press the OK button, you get the file. A if(Flag = =jfilechooser.approve_option) { + //Get the file thef =fc.getselectedfile (); -System. out. println ("Open File----"+f.getname ()); $ } the } the the Private voidReadFile ()//Save File the { - String FileName; in the //set the title of the Save File dialog box theFc.setdialogtitle ("Save File"); About the //the dialog box for saving the file is displayed here the Try { theFlag =fc.showsavedialog (frm); +}Catch(Headlessexception He) { -System. out. println ("Save File Dialog error!"); the }Bayi the //If you press the OK button, you get the file. the if(Flag = =jfilechooser.approve_option) { - //get the file you entered to save -f =fc.getselectedfile (); the //Get file name theFileName =Fc.getname (f); the //You can also use Filename=f.getname (); theSystem. out. println (fileName); - } the } the the //button Listener class inner class94 classAction implements ActionListener { the Public voidactionperformed (ActionEvent e) { the //decide which button was clicked. the if(E.getsource () = =Open)98 openFile (); About Else if(E.getsource () = =Read) - readFile ();101 }102 }103 104 Public Static voidMain (string[] args) { the NewFilechooser ();106 }107}
File Save in Java, Open File dialog box