服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - JAVA教程 - Java Swing组件JFileChooser用法实例分析

Java Swing组件JFileChooser用法实例分析

2021-02-04 11:03pzy4447 JAVA教程

这篇文章主要介绍了Java Swing组件JFileChooser用法,结合实例形式分析了java Swing组件JFileChooser文件选择器的功能、使用方法及相关注意事项,需要的朋友可以参考下

本文实例讲述了java swing组件jfilechooser用法。分享给大家供大家参考,具体如下:

jfilechooser文件选择器是swing中经常用到的一个控件。它的使用主要包含以下几个参数:

1.当前路径。也就是它第一次打开时所在的路径,许多软件喜欢设置为桌面。

2.文件过滤器。通过设置文件过滤器,只有特定类型的文件是可见的,比如文本,音频,等。

3.选择模式。包含三种情况:仅文件, 仅目录, 文件或目录。

4.是否允许多选。

jfilechooser的参数当然不止以上4种,它还有很多高级选项,比如你可以对文件的显示图标进行定制等,由于不经常用,这里不再介绍。

有2个地方要注意:

1.文件过滤器建议使用filenameextensionfilter,它是filefilter的子类,以非常方便的方法实现了过滤器。用法见代码。

2.getselectedfiles()方法,它只在ismultiselectionenable()方法返回true是有效。也就是说,如果你不允许多选,则只能使用getselectedfile()方法,否则只能得到一个空的文件列表。

下面通过一个demo来展示它的基本用法。

?
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package awtdemo;
import java.io.file;
import javax.swing.jfilechooser;
import javax.swing.joptionpane;
import javax.swing.filechooser.filenameextensionfilter;
import javax.swing.filechooser.filesystemview;
/**
 *
 * @author pzy
 */
@suppresswarnings("serial")
public class jfilechooserframe extends javax.swing.jframe {
  /**
   * creates new form jfilechooserframe
   */
  public jfilechooserframe() {
    initcomponents();
  }
  /**
   * this method is called from within the constructor to initialize the form.
   * warning: do not modify this code. the content of this method is always
   * regenerated by the form editor.
   */
  @suppresswarnings({ "unchecked", "rawtypes" })
  // <editor-fold defaultstate="collapsed" desc="generated code">
  private void initcomponents() {
    filefilterisbg = new javax.swing.buttongroup();
    ismultiselectbg = new javax.swing.buttongroup();
    jpanel1 = new javax.swing.jpanel();
    text_rb = new javax.swing.jradiobutton();
    video_rb = new javax.swing.jradiobutton();
    audio_rb = new javax.swing.jradiobutton();
    all_rb = new javax.swing.jradiobutton();
    jpanel2 = new javax.swing.jpanel();
    jcombobox1 = new javax.swing.jcombobox();
    multiselect_rb = new javax.swing.jradiobutton();
    singleselect_rb = new javax.swing.jradiobutton();
    jpanel3 = new javax.swing.jpanel();
    jbutton1 = new javax.swing.jbutton();
    setdefaultcloseoperation(javax.swing.windowconstants.exit_on_close);
    setlocationbyplatform(true);
    jpanel1.setborder(javax.swing.borderfactory.createtitledborder("文件类型"));
    filefilterisbg.add(text_rb);
    text_rb.settext("文本");
    filefilterisbg.add(video_rb);
    video_rb.settext("视频");
    filefilterisbg.add(audio_rb);
    audio_rb.settext("音频");
    filefilterisbg.add(all_rb);
    all_rb.setselected(true);
    all_rb.settext("所有");
    javax.swing.grouplayout jpanel1layout = new javax.swing.grouplayout(jpanel1);
    jpanel1.setlayout(jpanel1layout);
    jpanel1layout.sethorizontalgroup(
      jpanel1layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(javax.swing.grouplayout.alignment.trailing, jpanel1layout.createsequentialgroup()
        .addcontainergap(javax.swing.grouplayout.default_size, short.max_value)
        .addcomponent(text_rb)
        .addgap(29, 29, 29)
        .addcomponent(video_rb)
        .addgap(35, 35, 35)
        .addcomponent(audio_rb)
        .addgap(39, 39, 39)
        .addcomponent(all_rb)
        .addgap(32, 32, 32))
    );
    jpanel1layout.setverticalgroup(
      jpanel1layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel1layout.createsequentialgroup()
        .addcontainergap()
        .addgroup(jpanel1layout.createparallelgroup(javax.swing.grouplayout.alignment.baseline)
          .addcomponent(video_rb)
          .addcomponent(text_rb)
          .addcomponent(audio_rb)
          .addcomponent(all_rb))
        .addcontainergap(javax.swing.grouplayout.default_size, short.max_value))
    );
    jpanel2.setborder(javax.swing.borderfactory.createtitledborder("选择模式"));
    jcombobox1.setmodel(new javax.swing.defaultcomboboxmodel(new string[] { "仅文件", "仅目录", "文件或目录" }));
    jcombobox1.addactionlistener(new java.awt.event.actionlistener() {
      public void actionperformed(java.awt.event.actionevent evt) {
        jcombobox1actionperformed(evt);
      }
    });
    ismultiselectbg.add(multiselect_rb);
    multiselect_rb.settext("可多选");
    ismultiselectbg.add(singleselect_rb);
    singleselect_rb.setselected(true);
    singleselect_rb.settext("不可多选");
    javax.swing.grouplayout jpanel2layout = new javax.swing.grouplayout(jpanel2);
    jpanel2.setlayout(jpanel2layout);
    jpanel2layout.sethorizontalgroup(
      jpanel2layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel2layout.createsequentialgroup()
        .addcontainergap()
        .addcomponent(jcombobox1, javax.swing.grouplayout.preferred_size, 144, javax.swing.grouplayout.preferred_size)
        .addgap(18, 18, 18)
        .addcomponent(multiselect_rb, javax.swing.grouplayout.preferred_size, 82, javax.swing.grouplayout.preferred_size)
        .addgap(18, 18, 18)
        .addcomponent(singleselect_rb, javax.swing.grouplayout.preferred_size, 82, javax.swing.grouplayout.preferred_size)
        .addcontainergap(14, short.max_value))
    );
    jpanel2layout.setverticalgroup(
      jpanel2layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel2layout.createsequentialgroup()
        .addcontainergap()
        .addgroup(jpanel2layout.createparallelgroup(javax.swing.grouplayout.alignment.baseline)
          .addcomponent(jcombobox1, javax.swing.grouplayout.preferred_size, javax.swing.grouplayout.default_size, javax.swing.grouplayout.preferred_size)
          .addcomponent(multiselect_rb)
          .addcomponent(singleselect_rb))
        .addcontainergap(16, short.max_value))
    );
    jbutton1.settext("开始");
    jbutton1.addactionlistener(new java.awt.event.actionlistener() {
      public void actionperformed(java.awt.event.actionevent evt) {
        jbutton1actionperformed(evt);
      }
    });
    javax.swing.grouplayout jpanel3layout = new javax.swing.grouplayout(jpanel3);
    jpanel3.setlayout(jpanel3layout);
    jpanel3layout.sethorizontalgroup(
      jpanel3layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel3layout.createsequentialgroup()
        .addgap(117, 117, 117)
        .addcomponent(jbutton1, javax.swing.grouplayout.preferred_size, 139, javax.swing.grouplayout.preferred_size)
        .addcontainergap(javax.swing.grouplayout.default_size, short.max_value))
    );
    jpanel3layout.setverticalgroup(
      jpanel3layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(jpanel3layout.createsequentialgroup()
        .addgap(26, 26, 26)
        .addcomponent(jbutton1, javax.swing.grouplayout.preferred_size, 32, javax.swing.grouplayout.preferred_size)
        .addcontainergap(19, short.max_value))
    );
    javax.swing.grouplayout layout = new javax.swing.grouplayout(getcontentpane());
    getcontentpane().setlayout(layout);
    layout.sethorizontalgroup(
      layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(layout.createsequentialgroup()
        .addcontainergap()
        .addgroup(layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
          .addcomponent(jpanel1, javax.swing.grouplayout.default_size, javax.swing.grouplayout.default_size, short.max_value)
          .addcomponent(jpanel2, javax.swing.grouplayout.default_size, javax.swing.grouplayout.default_size, short.max_value)
          .addgroup(layout.createsequentialgroup()
            .addcomponent(jpanel3, javax.swing.grouplayout.default_size, javax.swing.grouplayout.default_size, short.max_value)
            .addgap(84, 84, 84)))
        .addcontainergap())
    );
    layout.setverticalgroup(
      layout.createparallelgroup(javax.swing.grouplayout.alignment.leading)
      .addgroup(layout.createsequentialgroup()
        .addgap(8, 8, 8)
        .addcomponent(jpanel1, javax.swing.grouplayout.preferred_size, javax.swing.grouplayout.default_size, javax.swing.grouplayout.preferred_size)
        .addgap(18, 18, 18)
        .addcomponent(jpanel2, javax.swing.grouplayout.preferred_size, javax.swing.grouplayout.default_size, javax.swing.grouplayout.preferred_size)
        .addgap(18, 18, 18)
        .addcomponent(jpanel3, javax.swing.grouplayout.preferred_size, javax.swing.grouplayout.default_size, javax.swing.grouplayout.preferred_size)
        .addcontainergap(javax.swing.grouplayout.default_size, short.max_value))
    );
    pack();
  }// </editor-fold>
  private void jcombobox1actionperformed(java.awt.event.actionevent evt) {
    // todo add your handling code here:
    string itemstring = jcombobox1.getselecteditem().tostring();
    if ("仅文件".equals(itemstring)) {
      fileselectionmode = jfilechooser.files_only;
    } else if ("仅目录".equals(itemstring)) {
      fileselectionmode = jfilechooser.directories_only;
    } else if ("文件或目录".equals(itemstring)) {
      fileselectionmode = jfilechooser.files_and_directories;
    }
  }
  private void jbutton1actionperformed(java.awt.event.actionevent evt) {
    // todo add your handling code here:
    filechooser = new jfilechooser();
    //初始化当前路径
    filesystemview fsv = filesystemview.getfilesystemview();
    file homefile =fsv.gethomedirectory();  //这便是读取桌面路径的方法了
    filechooser.setcurrentdirectory(homefile);
    //初始化文件过滤器
    if (text_rb.isselected()) {
      filter = new filenameextensionfilter("文本文件", "log", "txt");
      filechooser.setfilefilter(filter);
    }
    if (video_rb.isselected()) {
      filter = new filenameextensionfilter("视频文件", "mp4", "mkv");
      filechooser.setfilefilter(filter);
    }
    if (audio_rb.isselected()) {
      filter = new filenameextensionfilter("音频文件", "mp3", "wma");
      filechooser.setfilefilter(filter);
    }
    //初始化选择模式
    filechooser.setfileselectionmode(fileselectionmode);
    //是否允许多选
    if (multiselect_rb.isselected()) {
      filechooser.setmultiselectionenabled(true);
    }
    else if(singleselect_rb.isselected()) {
      filechooser.setmultiselectionenabled(false);
    }
    //打开文件选择器
    int i = filechooser.showdialog(this, "选择");
    if(i == jfilechooser.approve_option){
      stringbuilder sb;
      if(filechooser.ismultiselectionenabled()){
      sb = new stringbuilder("您选择了以下文件:");
      file [] files = filechooser.getselectedfiles();
      for (file file : files) {
        sb.append("\n");
        sb.append(file.getname());
      }
      }
      else{
        file file = filechooser.getselectedfile();
        sb = new stringbuilder("您选择的文件是:");
         sb.append("\n");
        sb.append(file.getname());
      }
      joptionpane.showmessagedialog(this, sb);
    }
  }
  /**
   * @param args the command line arguments
   */
  public static void main(string args[]) {
    /* set the nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" look and feel setting code (optional) ">
    /* if nimbus (introduced in java se 6) is not available, stay with the default look and feel.
     * for details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
      for (javax.swing.uimanager.lookandfeelinfo info : javax.swing.uimanager.getinstalledlookandfeels()) {
        if ("nimbus".equals(info.getname())) {
          javax.swing.uimanager.setlookandfeel(info.getclassname());
          break;
        }
      }
    } catch (classnotfoundexception ex) {
      java.util.logging.logger.getlogger(jfilechooserframe.class.getname()).log(java.util.logging.level.severe, null, ex);
    } catch (instantiationexception ex) {
      java.util.logging.logger.getlogger(jfilechooserframe.class.getname()).log(java.util.logging.level.severe, null, ex);
    } catch (illegalaccessexception ex) {
      java.util.logging.logger.getlogger(jfilechooserframe.class.getname()).log(java.util.logging.level.severe, null, ex);
    } catch (javax.swing.unsupportedlookandfeelexception ex) {
      java.util.logging.logger.getlogger(jfilechooserframe.class.getname()).log(java.util.logging.level.severe, null, ex);
    }
    //</editor-fold>
    /* create and display the form */
    java.awt.eventqueue.invokelater(new runnable() {
      public void run() {
        new jfilechooserframe().setvisible(true);
      }
    });
  }
  private jfilechooser filechooser;
  private filenameextensionfilter filter;
  private int fileselectionmode = jfilechooser.files_only;
  // variables declaration - do not modify
  private javax.swing.jradiobutton all_rb;
  private javax.swing.jradiobutton audio_rb;
  private javax.swing.buttongroup filefilterisbg;
  private javax.swing.buttongroup ismultiselectbg;
  private javax.swing.jbutton jbutton1;
  @suppresswarnings("rawtypes")
 private javax.swing.jcombobox jcombobox1;
  private javax.swing.jpanel jpanel1;
  private javax.swing.jpanel jpanel2;
  private javax.swing.jpanel jpanel3;
  private javax.swing.jradiobutton multiselect_rb;
  private javax.swing.jradiobutton singleselect_rb;
  private javax.swing.jradiobutton text_rb;
  private javax.swing.jradiobutton video_rb;
  // end of variables declaration
}

运行效果如下:

Java Swing组件JFileChooser用法实例分析

Java Swing组件JFileChooser用法实例分析

Java Swing组件JFileChooser用法实例分析

希望本文所述对大家java程序设计有所帮助。

原文链接:http://www.cnblogs.com/pzy4447/p/6095452.html

延伸 · 阅读

精彩推荐