Java – adjusts the selected file to filefilter in Jfilechooser

I write a graph editor in Java This application can choose to export to various standard image formats, such as jpg,. Png et al When the user clicks file - > export, you will get a Jfilechooser containing multiple filefilters for jpg,. Png wait

Now this is my question:

Is there any way to adjust the default extension to the selected file filter? For example If the file is named "lolcat", when PNG filter is selected, the default option should be "lolcat. PNG". When JPG file filter is selected, the default value should be automatically changed to "lolcat. JPG"

Is that possible? What shall I do?

Editor: according to the following answers, I wrote some code But it hasn't finished its work yet I have added a propertychangelister to file_ FILTER_ CHANGED_ Property, but in this method, it seems that getselectedfile() returns null This is the code

package nl.helixsoft;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.Propertychangelistener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;

public class JFileChooserTest {
    public class SimpleFileFilter extends FileFilter {
        private String desc;
        private List<String> extensions;
        private boolean showDirectories;

        /**
         * @param name example: "Data files"
         * @param glob example: "*.txt|*.csv"
         */
        public SimpleFileFilter (String name,String globs) {
            extensions = new ArrayList<String>();
            for (String glob : globs.split("\\|")) {
                if (!glob.startsWith("*.")) 
                    throw new IllegalArgumentException("expected list of globs like \"*.txt|*.csv\"");
                // cut off "*"
                // store only lower case (make comparison case insensitive)
                extensions.add (glob.substring(1).toLowerCase());
            }
            desc = name + " (" + globs + ")";
        }

        public SimpleFileFilter(String name,String globs,boolean showDirectories) {
            this(name,globs);
            this.showDirectories = showDirectories;
        }

        @Override
        public boolean accept(File file) {
            if(showDirectories && file.isDirectory()) {
                return true;
            }
            String fileName = file.toString().toLowerCase();

            for (String extension : extensions) {   
                if (fileName.endsWith (extension)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public String getDescription() {
            return desc;
        }

        /**
         * @return includes '.'
         */
        public String getFirstExtension() {
            return extensions.get(0);
        }
    }

    void export() {
        String documentTitle = "lolcat";

        final JFileChooser jfc = new JFileChooser();
        jfc.setDialogTitle("Export");
        jfc.setDialogType(JFileChooser.SAVE_DIALOG);
        jfc.setSelectedFile(new File (documentTitle));
        jfc.addChoosableFileFilter(new SimpleFileFilter("JPEG","*.jpg"));
        jfc.addChoosableFileFilter(new SimpleFileFilter("PNG","*.png"));
        jfc.addPropertychangelistener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY,new Propertychangelistener() {
            public void propertyChange(PropertyChangeEvent arg0) {
                System.out.println ("Property changed");
                String extold = null;
                String extnew = null;
                if (arg0.getOldValue() == null || !(arg0.getOldValue() instanceof SimpleFileFilter)) return;
                if (arg0.getNewValue() == null || !(arg0.getNewValue() instanceof SimpleFileFilter)) return;
                SimpleFileFilter oldValue = ((SimpleFileFilter)arg0.getOldValue());
                SimpleFileFilter newValue = ((SimpleFileFilter)arg0.getNewValue());
                extold = oldValue.getFirstExtension();
                extnew = newValue.getFirstExtension();
                String filename = "" + jfc.getSelectedFile();
                System.out.println ("file: " + filename + " old: " + extold + ",new: " + extnew);
                if (filename.endsWith(extold)) {
                    filename.replace(extold,extnew);
                } else {
                    filename += extnew;
                }
                jfc.setSelectedFile(new File (filename));
            }
        });
        jfc.showDialog(frame,"export");
    }

    JFrame frame;

    void run() {
        frame = new JFrame();
        JButton btn = new JButton ("export");
        frame.add (btn);
        btn.addActionListener (new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                export();
            }
        });
        frame.setSize (300,300);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokelater(new Runnable() {     
            public void run() {
                JFileChooserTest x =  new JFileChoosertest();
                x.run();
            }
        });     
    }
}

resolvent

Solution

It looks like you can listen to Jfilechooser to change the file_ FILTER_ CHANGED_ Property property, and then use setselectedfile() to change the extension of the selected file appropriately

Editor: you're right. This solution won't work It turns out that when the file filter is changed, if the file type of the selected file does not match the new filter, the selected file is deleted That's why when you try getselectedfile (), you get null

Will you consider joining the extension later? When I write Jfilechooser, I usually add the extension after the user selects the file to use and click Save:

if (result == JFileChooser.APPROVE_OPTION)
{
  File file = fileChooser.getSelectedFile();
  String path = file.getAbsolutePath();

  String extension = getExtensionForFilter(fileChooser.getFileFilter());

  if(!path.endsWith(extension))
  {
    file = new File(path + extension);
  }
}
fileChooser.addPropertychangelistener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY,new Propertychangelistener()
{
  public void propertyChange(PropertyChangeEvent evt)
  {
    FileFilter filter = (FileFilter)evt.getNewValue();

    String extension = getExtensionForFilter(filter); //write this method or some equivalent

    File selectedFile = fileChooser.getSelectedFile();
    String path = selectedFile.getAbsolutePath();
    path.substring(0,path.lastIndexOf("."));

    fileChooser.setSelectedFile(new File(path + extension));
  }
});

The above is the Java collected and sorted out by programming home for you - adjust the selected file to the filefilter in Jfilechooser. I hope this article can help you solve the program development problems encountered by Java - adjust the selected file to the filefilter in Jfilechooser.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>