How can I use the download file option in JAVA Swing?

I am new to Swing and want to implement the download file function in my Swing code, which will allow the user to either save or open a specific file.

I looked at JFileChooser.showOpenDialog and showSaveDialog, but I do not want to use it, because it gives me the ability to select any file from the file system.

Hope my problem is clear. Please help me with this.

+3
source share
2 answers

You want to use them and add a filter. For example:

    JFileChooser chooser = new JFileChooser();
    // Note: source for ExampleFileFilter can be found in FileChooserDemo,
    // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
    ExampleFileFilter filter = new ExampleFileFilter();
    filter.addExtension("jpg");
    filter.setDescription("JPG & GIF Images");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showSaveDialog(parent);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
       System.out.println("You chose to open this file: " +
            chooser.getSelectedFile().getName());
    }

Only JPG and GIF files will be displayed here. Example stolen from here

: , ExampleFileFilter abstact FileFilter

: , , Runtime.getRuntime.exec( ", .doc" ), .

, , JFileChooser. - , , :

    JFileChooser chooser = new JFileChooser();
    // Note: source for ExampleFileFilter can be found in FileChooserDemo,
    // under the demo/jfc directory in the Java 2 SDK, Standard Edition.

    String selectedFile = "The suggested save name.";
    chooser.setSelectedFile(selectedFile);

    ExampleFileFilter filter = new ExampleFileFilter();
    String extension = "Do something to find your extension";
    filter.addExtension(extension);
    filter.setDescription("JPG & GIF Images");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showSaveDialog(parent);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
       System.out.println("You chose to open this file: " +
            chooser.getSelectedFile().getName());
       //then write your code to write to disk
    }

, .

+5

. , , .

/ . , /.

+1

Source: https://habr.com/ru/post/1705019/


All Articles