本文實例講述了Java Swing組件文件選擇器JFileChooser簡單用法。分享給大家供大家參考,具體如下:
先來看效果:
說明:選擇文件或者文件夾。本例子就直接在控制臺輸出文件或者文件夾的路徑。實際開發中,就可以將文件或文件夾的路徑封裝為File的實例來使用了。
具體代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package awtDemo; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; @SuppressWarnings ( "serial" ) public class FileChooser extends JFrame implements ActionListener{ JButton open= null ; public static void main(String[] args) { new FileChooser(); } public FileChooser(){ open= new JButton( "open" ); this .add(open); this .setBounds( 400 , 200 , 100 , 100 ); this .setVisible( true ); this .setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); open.addActionListener( this ); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub JFileChooser jfc= new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES ); jfc.showDialog( new JLabel(), "選擇" ); File file=jfc.getSelectedFile(); if (file.isDirectory()){ System.out.println( "文件夾:" +file.getAbsolutePath()); } else if (file.isFile()){ System.out.println( "文件:" +file.getAbsolutePath()); } System.out.println(jfc.getSelectedFile().getName()); } } |
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://www.cnblogs.com/linfenghp/p/5977761.html