溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在Java中使用JFileChooser組件

發(fā)布時(shí)間:2021-04-01 17:33:07 來(lái)源:億速云 閱讀:146 作者:Leah 欄目:編程語(yǔ)言

這篇文章將為大家詳細(xì)講解有關(guān)如何在Java中使用JFileChooser組件,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

JFileChooser文件選擇器是Swing中經(jīng)常用到的一個(gè)控件。它的使用主要包含以下幾個(gè)參數(shù):

1.當(dāng)前路徑。也就是它第一次打開(kāi)時(shí)所在的路徑,許多軟件喜歡設(shè)置為桌面。

2.文件過(guò)濾器。通過(guò)設(shè)置文件過(guò)濾器,只有特定類型的文件是可見(jiàn)的,比如文本,音頻,等。

3.選擇模式。包含三種情況:僅文件, 僅目錄, 文件或目錄。

4.是否允許多選。

JFileChooser的參數(shù)當(dāng)然不止以上4種,它還有很多高級(jí)選項(xiàng),比如你可以對(duì)文件的顯示圖標(biāo)進(jìn)行定制等,由于不經(jīng)常用,這里不再介紹。

有2個(gè)地方要注意:

1.文件過(guò)濾器建議使用FileNameExtensionFilter,它是FileFilter的子類,以非常方便的方法實(shí)現(xiàn)了過(guò)濾器。用法見(jiàn)代碼。

2.getSelectedFiles()方法,它只在isMultiSelectionEnable()方法返回true是有效。也就是說(shuō),如果你不允許多選,則只能使用getSelectedFile()方法,否則只能得到一個(gè)空的文件列表。

下面通過(guò)一個(gè)demo來(lái)展示它的基本用法。

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("開(kāi)始");
    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();
    //初始化當(dāng)前路徑
    FileSystemView fsv = FileSystemView.getFileSystemView();
    File homeFile =fsv.getHomeDirectory();  //這便是讀取桌面路徑的方法了
    fileChooser.setCurrentDirectory(homeFile);
    //初始化文件過(guò)濾器
    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);
    }
    //打開(kāi)文件選擇器
    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
}

運(yùn)行效果如下:

如何在Java中使用JFileChooser組件

如何在Java中使用JFileChooser組件

如何在Java中使用JFileChooser組件

關(guān)于如何在Java中使用JFileChooser組件就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI