JFileChooser file name extention queistion

hi i would like to know if it is possible to place a file extention in the filename section when you open the save dialog. So as when the user types a file name in the file extention is added automaticly to only allow the user to save in .png. My code is as follows.
private void screenshot()
          /** currently no dialog to confirm action as remains
          on screen when saving screenshot! **/
          int status;
          JFileChooser fc = new JFileChooser();
          fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
          try {
                    Rectangle rect = new Rectangle(Toolkit.getDefaultToolkit ().getScreenSize ());
                    BufferedImage image = new Robot().createScreenCapture(rect);
                    try {
                         fc.addChoosableFileFilter(new PNGFilter());
                        status = fc.showSaveDialog(information);
                        if(status == JFileChooser.APPROVE_OPTION)
                        File selFile = fc.getSelectedFile();
                        ImageIO.write(image, "png", selFile);
                        JOptionPane.showMessageDialog(information, "File saved to "+ selFile);     
                    } catch (IOException e) {
                              Error.SaveError(e);
                    catch (AWTException e) {
                         Error.AbstractWindowToolkit(e);
}

You can always check selFile's name, and if it
doesn't end with .png replace it
with a new File with the same name, but with .png
added on.Thanks for that. I have done just that and it works great now.
if(getExtension(selFile).equals("NO_EXTENSION"))
                           selFile = new File(selFile.toString() + ".png");
                       }

Similar Messages

  • JFileChooser "File Name" field

    Hi,
    I am trying to use a JFileChooser as a component within a JDialog, and everything works fine, except that I do not understand how I can get the value of a filename typed into the "File Name:" field on the form. I've read the "JFileChooser" Java doco about five times and I can't see anything that would give me access to this field. GetName() appears to be a red herring.
    Anyone got any ideas?
    Thanks,
    Tim

    Thanks for your swift reply.
    Unfortunately perhaps I wasn't quite clear - I have added the JFileChooser as a component to a JDialog, not run it standalone via showDialog() or similar.
    I am trying to get the user to select a directory and type a file name that a new file can be saved into.
    Here is the code that displays the chooser:
       private JPanel saveFilePnl(String folder)
          JPanel panel = new JPanel(new BorderLayout());
          panel.add(new JLabel("<html>Select the folder to save the new sequence into,<br>" +
                               "and type in an appropriate File Name:<br>"),"North");
          saveFileChooser.setCurrentDirectory(new File(folder));
          SimpleFileFilter filter = new SimpleFileFilter("xml", "Nucleotide Sequences"); 
          saveFileChooser.setFileFilter(filter);
          saveFileChooser.setControlButtonsAreShown(false);
          saveFileChooser.setBorder(BorderFactory.createCompoundBorder
                                (BorderFactory.createEtchedBorder(),
                                 BorderFactory.createEmptyBorder(8,8,8,8) ));
          panel.add(saveFileChooser, "Center");
          return panel;
    }This panel is added to a card on a CardLayout JDialog. After the user selects a folder and types in a filename I want to verify that they have done so before moving on to the next card. So I need to ensure that there is a name in the "File Name:" field on the chooser.
    Thanks,
    Tim

  • Can JFileChooser file name field return all entered chars

    In JFileChooser, if I want to get all entered characters from file name field, is there a method I can call?
    I used method chooserUI.getFileName() or chooser.getSelectedFile(). These two methods returned texts which missed back slash and forward slash. I want to get everything what I entered in file name field. I searched and read related JFileChooser topic, but there isn't a topic about this. Can any of you know what I can do?
    Thank you very much.

    JFileChooser isn't for entering text, it's for selecting files. If you put for example "abc/def" in the filename box, it's going to interpret that as "file def in directory abc" and your getFileName() will return "def". (You'll notice that getFileName() doesn't return the directory path, just the filename part of it, right?)

  • JFileChooser File Name

    Hi!
    I'm using a JFileChooser to save in a local folder a file stored in my database and I'd like to set the File Name when I open the FileChooser, do you know how to do it ??
    Thanks !!
    TLLI

    JFileChooser.setSelectedFile()?

  • FILE NAME WITH FILE EXTENTIONS

    HI EXPERTS!!
    I WANT TO GET THE FULL FILE NAME STRORED IN THE SERVER FOLDER. I USED  FM RZL_READ_DIR_LOCAL BUT I AM GETTING ONLY 32 DIGITS OF NAME NOT FULL NAME AND ALSO SIZE PARAMETER IS CONCATENATING WITH NAME.
    I WANT THE FILE NAME WITH FILE EXTENTIONS(TXT. .PDF ETC)..
    PLZ SUGGEST ME HOW TO GET THE SAME..
    PLZ REPLYE ME..
    MAHESH

    Hi Mahesh,
    Try the below FM in the below code.
      DATA:
        LV_PERMISSION(10),                 " Permission
        LV_H2,                             " H2
        LV_FLNM(13),                       " File name
        LV_USER(10),                       " User
        LV_GROUP(10),                      " Group
        LV_SIZE(15),                       " Size
        LV_MONTH(3),                       " Month
        LV_DAY_C(2),                       " Day
        LV_YEAR(5),                        " Year
        LV_FILE_NAME       TYPE FILE_NAME, " Filename
        LV_JUNK,                           " Junk
        RETURN_CODE      TYPE I.           " Return code
      DATA:
        CMD_PARAMS LIKE SXPGCOLIST-PARAMETERS,
                                           " External prg.parameters
        CMD_OUTPUT TYPE BTCXPM OCCURS 0,   " Log message
        STATUS TYPE EXTCMDEXEX-STATUS.     " Status
      CONSTANTS:
        LC_DIR TYPE C VALUE 'd'.           " Directory
      FIELD-SYMBOLS: <CMD_OUTPUT_LINE> LIKE LINE OF CMD_OUTPUT.
      CMD_PARAMS = PV_DIRECTORY.
      CLEAR CMD_OUTPUT.
      CALL FUNCTION 'SXPG_CALL_SYSTEM'
           EXPORTING
                COMMANDNAME                = 'Y_LS_LN'
                ADDITIONAL_PARAMETERS      = CMD_PARAMS
           IMPORTING
                STATUS                     = STATUS
                EXITCODE                   = RETURN_CODE
           TABLES
                EXEC_PROTOCOL              = CMD_OUTPUT
           EXCEPTIONS
                NO_PERMISSION              = 1
                COMMAND_NOT_FOUND          = 2
                PARAMETERS_TOO_LONG        = 3
                SECURITY_RISK              = 4
                WRONG_CHECK_CALL_INTERFACE = 5
                PROGRAM_START_ERROR        = 6
                PROGRAM_TERMINATION_ERROR  = 7
                X_ERROR                    = 8
                PARAMETER_EXPECTED         = 9
                TOO_MANY_PARAMETERS        = 10
                ILLEGAL_COMMAND            = 11
                OTHERS                     = 12.
    Check Status first then check sy-subrc
      CASE SY-SUBRC.
        WHEN 0.
          CASE STATUS.
            WHEN 'F'.
              MESSAGE I057(YS) WITH 'SXPG_CALL_SYSTEM'(002).
              GF_EXIT = GC_TRUE.
            WHEN 'E'.
              MESSAGE I058(YS) WITH 'SXPG_CALL_SYSTEM'(002).
              GF_EXIT = GC_TRUE.
            WHEN 'S'.
              MESSAGE I059(YS) WITH 'SXPG_CALL_SYSTEM'(002).
              GF_EXIT = GC_TRUE.
            WHEN 'C'.
              MESSAGE I061(YS) WITH 'SXPG_CALL_SYSTEM'(002).
              GF_EXIT = GC_TRUE.
          ENDCASE.                         " CASE STATUS.
        WHEN 1.
          MESSAGE I048(YS) WITH 'SXPG_CALL_SYSTEM'(002).
          GF_EXIT = GC_TRUE.
        WHEN 2.
          MESSAGE I049(YS) WITH 'Y_LS_LN'(003).
          GF_EXIT = GC_TRUE.
        WHEN 3.
          MESSAGE I050(YS) WITH 'SXPG_CALL_SYSTEM'(002).
          GF_EXIT = GC_TRUE.
        WHEN 9.
          MESSAGE I054(YS) WITH 'SXPG_CALL_SYSTEM'(002).
          GF_EXIT = GC_TRUE.
        WHEN 10.
          MESSAGE I055(YS) WITH 'SXPG_CALL_SYSTEM'.
          GF_EXIT = GC_TRUE.
        WHEN 11.
          MESSAGE I056(YS) WITH 'SXPG_CALL_SYSTEM'(002).
          GF_EXIT = GC_TRUE.
        WHEN OTHERS.
          MESSAGE I022(YS) WITH SY-SUBRC.
          GF_EXIT = GC_TRUE.
      ENDCASE.                             " CASE SY-SUBRC.
      IF GF_EXIT = ' '.
        READ TABLE CMD_OUTPUT ASSIGNING <CMD_OUTPUT_LINE> INDEX 1.
        IF SY-SUBRC = 0.
          CONDENSE <CMD_OUTPUT_LINE>-MESSAGE.
          IF <CMD_OUTPUT_LINE>-MESSAGE CS 'total' OR
             <CMD_OUTPUT_LINE>-MESSAGE CS 'TOTAL'.
            DELETE CMD_OUTPUT INDEX 1.
          ENDIF.
        ENDIF.
        LOOP AT CMD_OUTPUT ASSIGNING <CMD_OUTPUT_LINE>.
          CONDENSE <CMD_OUTPUT_LINE>-MESSAGE.
          SPLIT <CMD_OUTPUT_LINE>-MESSAGE AT SPACE INTO
                                          LV_PERMISSION
                                          LV_H2
                                          LV_USER
                                          LV_GROUP
                                          LV_SIZE
                                          LV_MONTH
                                          LV_DAY_C
                                          LV_YEAR
                                          LV_FILE_NAME
                                          LV_JUNK.
          IF LV_PERMISSION(1) = LC_DIR.
            CONTINUE.
          ELSE.
            LV_FLNM = LV_FILE_NAME(13).
            TRANSLATE LV_FLNM TO UPPER CASE.
            IF LV_FLNM = '1W_FIARFUNNEL'.
              PT_FILE-FILE_NAME = LV_FILE_NAME.
              APPEND PT_FILE.
            ENDIF.                         " IF LV_FLNM = '1D_FIARFUNNEL'.
          ENDIF.                           " IF lv_permission(1) = ...
        ENDLOOP.                           " LOOP AT CMD_OUTPUT
      ENDIF.                               " IF GF_EXIT = ' '.

  • Suggest file name in JFileChooser?

    I'm a newbie (student) to both Swing and Java in general. In using JFileChooser, It occurred to me that it would be nice to offer a suggested file name when saving files.
    For those of you who have used MS Word, when one saves a new file, Word offers the document title or a few words of the document's first line as a suggested file name. This suggestion is displayed in the file name textbox of the save file dialog.
    Is it possible to do this sort of thing in Java and with JFileChooser? If so, how?
    Thanks in advance for any feedback.

    JFileChooser  fc = new JFileChooser(".");
    fc.setSelectedFile(new File("AnyFileNameYouWant.txt"));

  • Easy -- default file name in JFileChooser

    Hello,
    I have a JFileChooser dialog ready and working. I select the directory, then input the file name and press Save.
    The enhancement I would like to add to the dialog would be displaying a default name already in the FileName field once the dialog is opened. For instance "REPORT_ONE_" and then I would only add some text to the end of the default name. This would save me from typing the "REPORT_ONE_" all the time as this would already be displayed in the filename field.
    I could add the "REPORT_ONE_" to the filename later, when saving the report. However appending anything to the filename "behind the scenes" is not acceptable by the customer. They need to see the filename, not guess it.
    Looking forward to your help, fellow forum users.
    Thank you!
    aulo

    Thank you, 5p given.
    However this is what I execute and in my file chooser dialog the filename field is still blank.
      ExampleFileFilter filter = new ExampleFileFilter();
        filter.addExtension("html");
        filter.addExtension("csv");
      JFileChooser chooser = new JFileChooser(new File("REPORT_ONE_"));
        chooser.setDialogTitle( "Save Report" );
        chooser.setFileSelectionMode(chooser.FILES_AND_DIRECTORIES);
        chooser.setFileFilter(filter);
        int returnVal = chooser.showSaveDialog(this);
        ...It is in try-catch, no errors are returned.
    Operating System: WindowsXP
    Java Version: 1.3.1

  • Make "File name" and "Files of type" fields read-only in JFileChooser

    I try to make the "File name" and "Files of type" fields read-only in JFileChooser dialog. Anybody
    knows how to do? Thanks.

    You mean so the user can't choose the name of the file to open or save? Not much point in even using a JFileChooser, then, is there? Or did I misunderstand the question?

  • How to position the cursor in File Name area in JFileChooser??

    Hi,
    I have been trying to position the cursor directly to filename area in JFileChooser. But no success.
    It positions itself at the directory path by default.
    How should I achieve this?
    The problem is that I do not know the name of this
    component used for File Name area hence difficult to
    use "requestFocus() or getFocus()" like methods.
    Thanks for your help.
    -Manoj

    Somewhere I saw a tip that explained how to do it, but I didn't keep a link to it. But basically it's like this: JFileChooser is a Container, so getComponent(n) will return the n-th component in the JFileChooser. One of them is the one you want to give the focus to, and I expect it will be a JTextField. A little experimentation should tell you which index you need to use.

  • How to set file name in a JFileChooser to be some default String?

    Dear all,
    I am tring to make my JFileChooser more user-friendly, so every time that a JFileChooser show up, I would like to fill the file name with some default String, instead of just leaving them blank.
    Does anybody know how to do this?
    Many Thanks!

    look up the set...() methods of the JFileChooser api docs

  • JFileChooser does not display japanese file names

    I am using JFileChooser to load some files in my application. I have some files which have japanese file names. When I try to load these files it does not even display these files for me to choose and then load them. Any ideas?

    Hi,
    I am trying to pick up data from an excel sheet and insert them into a database. However, once updated, they end up with '?' values.
    I have tried to make font.properties.ja as the default font.properties file, which failed to display Japanese characters.
    Any suggestions?
    This is a part of my code:
    String sJIS = "";
    sJIS = new String(cell1.getStringCellValue().getBytes("8859_1"), "JISAutoDetect");
    String sUTF = "";
    sUTF = new String(cell1.getStringCellValue().getBytes(), "UTF-16");
    System.out.println("sUTF" + sUTF + " " + "sJIS" + sJIS);
    Thanks,

  • JFileChooser Replacing File Name

    I am using a JFileChooser as a "Save" dialog box. Here is the situation: the user has entered a proposed file name, then he/she double clicks on a directory where the file should be saved. Then they click "Save". At the point the user double clicked the directory, his/her proposed file name has been replaced by the directory name. The user may not notice it before he/she clicks "Save" thus creating a file in the directory with the same name as the directory.
    This "proposed file name replacing" behavior is fine when the user clicks a file but shouldn't happen when a directory is selected. The common Windows filechooser gets this right.
    Is it possible to make JFileChooser stop doing this?
    Thanks!

    When you doubleclick, you have to check wether the selection is a file or a directory with the isDirectory() method. You can than decide to overwrite the Stringvalue or not, depending on the case.
    KR,
    Jan

  • How do I batch the file name (without extention) into the keyword in the metadata

    I am trying to use a keyword into sets of images, each of the images on the set contains in the file name what I want for keyword and an extension.
    Example,
    File names:   
    WD111_main
    WD111_01
    WD111_02
    I want all of them to have on the metadata just WD111.
    help?!?!

    You will need to do this with a text field and a Javascript that executes on open.

  • How to set selected file in FileChooser showSaveDialog to default file name

    Hi,
    How do I set selected file in JavaFX 2.0 FileChooser showSaveDialog, so I can prompt the user with a suggested default file name?
    I am converting a Java Swing application I wrote a few years ago to JavaFX 2.0.
    In the Swing application, I use setSelectedFile() as follows:
    JFileChooser jFileChooser = new JFileChooser();
    jFileChooser.setSelectedFile(new File(backupfile));
    jFileChooser.setCurrentDirectory(new File(outputDirectory));
    FileFilter filter = new FileNameExtensionFilter("Comma Delimited (*.csv)", "csv");
    jFileChooser.addChoosableFileFilter(filter);
    jFileChooser.setFileFilter(filter);
    filter = new FileNameExtensionFilter("XML Document (*.xml)", "xml");
    jFileChooser.addChoosableFileFilter(filter);
    jFileChooser.setAcceptAllFileFilterUsed(false);
    jFileChooser.setDialogTitle("Export File");
    int returnVal = jFileChooser.showDialog(jFrame, "Export");
    This would show a file chooser with the file name text field pre-populated with a default backup file name.
    I can't find an equivalent in JavaFX.
    Also, in the Swing application, I was able to determine which extension filter was selected at run time using getFileFilter().getDescription() as follows:
    String extension = jFileChooser.getFileFilter().getDescription();
    if (extension.equals("XML Document (*.xml)")) { ...
    I can't find an equivalent in JavaFX.
    Thanks,
    Barry

    You can use the open sequence file method on the application manager (then you only need to wire the file path)
    Rodéric L
    Certified LabVIEW Architect

  • How to get the full path instead of just the file name, in �FileChooser� ?

    In the FileChooserDemo example :
    In the statement : log.append("Saving: " + file.getName() + "." + newline);
    �file.getName()� returns the �file name�.
    My question is : How to get the full path instead of just the file name,
    e.g. C:/xdirectory/ydirectory/abc.gif instead of just abc.gif
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class FileChooserDemo extends JFrame {
    static private final String newline = "\n";
    public FileChooserDemo() {
    super("FileChooserDemo");
    //Create the log first, because the action listeners
    //need to refer to it.
    final JTextArea log = new JTextArea(5,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);
    //Create a file chooser
    final JFileChooser fc = new JFileChooser();
    //Create the open button
    ImageIcon openIcon = new ImageIcon("images/open.gif");
    JButton openButton = new JButton("Open a File...", openIcon);
    openButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    int returnVal = fc.showOpenDialog(FileChooserDemo.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    //this is where a real application would open the file.
    log.append("Opening: " + file.getName() + "." + newline);
    } else {
    log.append("Open command cancelled by user." + newline);
    //Create the save button
    ImageIcon saveIcon = new ImageIcon("images/save.gif");
    JButton saveButton = new JButton("Save a File...", saveIcon);
    saveButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    int returnVal = fc.showSaveDialog(FileChooserDemo.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    //this is where a real application would save the file.
    log.append("Saving: " + file.getName() + "." + newline);
    } else {
    log.append("Save command cancelled by user." + newline);
    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(openButton);
    buttonPanel.add(saveButton);
    //Explicitly set the focus sequence.
    openButton.setNextFocusableComponent(saveButton);
    saveButton.setNextFocusableComponent(openButton);
    //Add the buttons and the log to the frame
    Container contentPane = getContentPane();
    contentPane.add(buttonPanel, BorderLayout.NORTH);
    contentPane.add(logScrollPane, BorderLayout.CENTER);
    public static void main(String[] args) {
    JFrame frame = new FileChooserDemo();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);

    simply use file.getPath()
    That should do it!Thank you !
    It takes care of the problem !!

Maybe you are looking for

  • How do I integrate Java Applet and JavaScript?

    Hi: This has been asked before, I have read the archives, yet I'm still left with some doubts, and some posts are VERY old and may not apply today. (sorry, some questions might seem stupid, this is my first applet). The purpose is to create a light w

  • External Optical Drive Not Recognized

    I've been using a Pioneer DVR111 external firewire drive for the last few months. Until tonight it's performed flawlessly. I ripped a couple of CDs into iTunes tonight, then when I tried to do another it wouldn't work. The CD wouldn't mount and the d

  • Lightroom 4.2/4.3RC: Library filter "Movies" has no effect

    I have imported photos and videos from my Canon EOS 5DII. I created a collection and all photos and videos are visible. When I set a filter to "Master Photos" all master photos are visible, but when I set a filter to "movies" no movies are visible. B

  • How do I motion track just like the Plugin CameraTracker 1.0?

    On the plugin CameraTracker, it automatically detects points that can be motion tracked, and it does it very well. What got me thinking, is that it also carries on tracking when a tracking point goes out of screen. Here's an example: I am using Camer

  • Particle Playground in RAM preview

    Using AE CS3 I've built a sequence involving the explosion effect of Particle Playground. I adjusted the Velocity Dispersion parameter to get a good expansion rate for the particles, using RAM preview at 50 percent resolutiion as a test bed. To my su