Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 142351
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T07:55:21+00:00 2026-05-11T07:55:21+00:00

I’m writing a diagram editor in java. This app has the option to export

  • 0

I’m writing a diagram editor in java. This app has the option to export to various standard image formats such as .jpg, .png etc. When the user clicks File->Export, you get a JFileChooser which has a number of FileFilters in it, for .jpg, .png etc.

Now here is my question:

Is there a way to have the extension of the default adjust to the selected file filter? E.g. if the document is named ‘lolcat’ then the default option should be ‘lolcat.png’ when the png filter is selected, and when the user selects the jpg file filter, the default should change to ‘lolcat.jpg’ automatically.

Is this possible? How can I do it?

edit: Based on the answer below, I wrote some code. But it doesn’t quite work yet. I’ve added a propertyChangeListener to the FILE_FILTER_CHANGED_PROPERTY, but it seems that within this method getSelectedFile() returns null. Here 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();             }         });          } } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T07:55:22+00:00Added an answer on May 11, 2026 at 7:55 am

    It looks like you can listen to the JFileChooser for a change on the FILE_FILTER_CHANGED_PROPERTY property, then change the extension of the selected file appropriately using setSelectedFile().


    EDIT: You’re right, this solution doesn’t work. It turns out that when the file filter is changed, the selected file is removed if its file type doesn’t match the new filter. That’s why you’re getting the null when you try to getSelectedFile().

    Have you considered adding the extension later? When I am writing a JFileChooser, I usually add the extension after the user has chosen a file to use and clicked ‘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));   } }); 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 84k
  • Answers 84k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer This will get you most of the way there: >>>… May 11, 2026 at 5:02 pm
  • Editorial Team
    Editorial Team added an answer Always include 1st and last block of file in hash.… May 11, 2026 at 5:02 pm
  • Editorial Team
    Editorial Team added an answer If you are looking for a "steady-state" solution, i.e. a… May 11, 2026 at 5:02 pm

Related Questions

I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I am currently running into a problem where an element is coming back from
Seemingly simple, but I cannot find anything relevant on the web. What is the
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.