簡體   English   中英

在指定目錄下啟動JFileChooser並僅顯示特定類型的文件

[英]Starting a JFileChooser at a specified directory and only showing files of a specific type

我有一個利用JFileChooser的程序。 簡而言之,完整的程序是一個GUI,它允許用戶操縱PNG和JPG。 我想這樣做,以便JFileChooser立即打開圖片目錄(Windows)。 當用戶打開其JFileChooser時,它將直接打開圖片庫C:\\ Users \\(USER)\\ Pictures

此外,最好只顯示特定類型的文件(PNG和JPG)。 許多程序似乎都可以做到這一點。 僅允許選擇特定文件。 JFileChooser允許這樣的事情嗎? 目前,我正在使用一種非常不可靠的解決方法來拒絕非PNG / JPG。

下面是指GUI的“瀏覽”按鈕,用戶可以在其中選擇要編輯的圖片,並將其顯示在屏幕上。

    try {
       int val = filec.showOpenDialog(GridCreator.this);
       if(val==JFileChooser.APPROVE_OPTION) {
          File unfiltered_picture = filec.getSelectedFile();
          //get the extension of the file
          extension=unfiltered_picture.getPath();
          int index=extension.indexOf(".");
          extension=extension.substring(index+1, extension.length());
          //if the file is not jpg, png, or jpeg, reject it and send a message to the user.
          if(!extension.matches("[jJ][pP][gG]") && !extension.matches("[pP][nN][gG]") && !extension.matches("[jJ][pP][eE][gG]")) {
             JOptionPane.showMessageDialog(null,
                                           "cannot load file. File must be of type png, jpeg, or jpg. \n Your file is of type " + extension,
                                            "Error: improper file",
                                            JOptionPane.OK_OPTION);
           //if the file is of the proper type, display it to the user on the img JLabel.
           } else {
              finalImage = ImageIO.read(unfiltered_picture);
              ImageIcon imgIcon = new ImageIcon();
              imgIcon.setImage(finalImage);
              img.setIcon(imgIcon);
              img.invalidate();
              h_divide.setValue(0);
              v_divide.setValue(0);
           }
       }
   } catch(IOException exception) {
        exception.printStackTrace();
   }

謝謝。

您需要使用要在其中開始的目錄構造JFileChooser ,然后將FileFilter傳遞到其中,然后再將其設置為visible。

    final JFileChooser fileChooser = new JFileChooser(new File("File to start in"));
    fileChooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }
            final String name = f.getName();
            return name.endsWith(".png") || name.endsWith(".jpg");
        }

        @Override
        public String getDescription() {
            return "*.png,*.jpg";
        }
    });
    fileChooser.showOpenDialog(GridCreator.this);

本示例過濾以“ .png”或“ .jpg”結尾的文件。

閱讀API: http : //docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html

在javadoc頁面的頂部,幾乎是您想要執行的操作的示例:

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}

通常,您要查找的類是FileFilter ,它是抽象的。 請參閱Javadoc: http : //docs.oracle.com/javase/6/docs/api/javax/swing/filechooser/FileFilter.html

簡而言之,這是一個靈活的文件選擇器例程。 它指定初始目錄和文件類型,並將結果提供為文件或完整路徑名。 您可能還想通過將setLookAndFeel命令放置在程序的Main入口點來將整個程序設置為純接口模式。

String[] fileChooser(Component parent, String dir, String typeFile) {
    File dirFile = new File(dir);
    JFileChooser chooser = new JFileChooser();
    // e.g. typeFile = "txt", "jpg", etc.
    FileNameExtensionFilter filter = 
        new FileNameExtensionFilter("Choose a "+typeFile+" file",
            typeFile); 
    chooser.setFileFilter(filter);
    chooser.setCurrentDirectory(dirFile);
    int returnVal = chooser.showOpenDialog(parent);

    String[] selectedDirFile = new String[2];
    if(returnVal == JFileChooser.APPROVE_OPTION) {
        // full path
        selectedDirFile[0] = chooser.getSelectedFile().getPath();
        // just filename
        selectedDirFile[1] = chooser.getSelectedFile().getName();
    }

    return selectedDirFile;
 }

try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
    e.printStackTrace();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM