Save in JFileChooser question

Hello everyone ...
I have a problem that has many answers on this site, but i cannot understand them (damn newbie me ! :)) ).
I use a JFileChooser to save a file and I want the extension of the file to be automatically appended to the filename. I use a filter for viewing files but i don't know how can I use a filter to save the files.
Thanks in advance,
Dan

class MyExtensionFilter extends FileFilter {
String myExtension = "";
public MyExtensionFilter(String myExtension) {
this.myExtension = myExtension;
public boolean accept(File file) {
return file.getName().endWith(myExtension);
public string getDescription() {
return myExtension;
File chosenFile = myFileChooser.getSelectedFile();
chosenFile = newFile(chosenFile.getAbsolutePath() + myFileFilter.getDescription();

Similar Messages

  • Save As operation Question

    Scenario - I have a web application that generates Excel documents that can be downloaded or opened directly. The web pages are a mixture of both ASP.NET and Classic ASP so the Excel file is actually generated as an HTML table. When a Save or Save As operation
    is done when the .xls file is downloaded a specified file name passed from the web page is used in the save operation. When you open the Excel file after saving Excel displays "The file you are trying to open "filename.xls" is in a different
    format than specified by the file extension...Do you want to open the file now?" informing me that the file is not a true xls file. When you continue with the opening the file it opens normally with no issues.
    Question or Possible issue: Taking one of these files after it has been saved to a location on the computer outside of the download folder, and perform a Save As operation to change the format to a true .xls file the theExisting File Name is not displayed in
    the File Name field. The Save as type defaults to Web Page which is understandable due to how the file is generated.
    I've tried this with actual Excel spreadsheets and the File Name field on the Save As operation is populated with the current name of the file and keeps it even if you change the Save as type.
    Main Question: Is there a setting somewhere in Excel to prevent the loss of the File Name?

    Hi,
    According to your description, the "The file you are trying to open "filename.xls" alert is from a feature called Extension Hardening, and you can find more information about it here. 
    http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx
    As you said and tested, Excel will retain the current file name in file name field when we save/save as the file. It's a default behavior. I suppose that the issue may be caused by the Excel that generated by web application.
    I recommend we try the 3 workarounds:
    1. Modify the ASP.NET program and make the file change to new excel format when generated
    Please see the thread:
    http://stackoverflow.com/questions/940045/how-to-suppress-the-file-corrupt-warning-at-excel-download
    2. Use "Office Migration Planning Manager" to convert the XLS to XLSX format.
    The toolkit also contains the Office File Converter (OFC), which enables bulk document conversions from binary to OpenXML formats. 
    Overview on Technet
    Download Link
    3. Use a macro to convert batch of XLS file to XLSX file and retain the file name.
    Sample code:
    Sub ProcessFiles()
    Dim Filename, Pathname, saveFileName As String
    Dim wb As Workbook
    Pathname = "C:\Users\myfolder1\Desktop\myfolder\Macro\"
    Filename = Dir(Pathname & "*.xls")
    Do While Filename <> ""
    Set wb = Workbooks.Open(Pathname & Filename)
    saveFilename = Replace(Filename, ".xlsx", ".xls")
    wb.SaveAs Filename:=Pathname & saveFilename, _
    FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
    ReadOnlyRecommended:=False, CreateBackup:=False
    wb.Close SaveChanges:=False
    Filename = Dir()
    Loop
    End Sub
    Regards,
    George Zhao
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • Save and delete question

    How to find out if there are other related records in another table.
    If there are other related record then delete is not allowed.
    For eample, Order has many items in it. 2 tables -Order Table and OrderItem table - one to many relationship.
    Then Can't delete a record in the order table if there are related record in the OrderItem table.
    I have 3 text fields. Enter data in it and then press the save button.
    It will save it to the database.
    how to force people to enter the data.
    That is, if they press save and if any of the 3 text fields is empty then
    show a message box saying need to fill in all text fields.
    How to find out if the text field is empty?
    How to save to multiple tables.
    That is, how to save the master table first then the detail tabes.
    For example, there is a order table and a orderItem table.
    When save button is clicked. must save to Order table first then to
    orderItem table.
    How to find out if the user is saving the data and that data already
    exists in database. So this is wrong. Can't have duplicate data.
    ----------------------------------------------

    For ur first question:
    use the transction to delete.if u found any of the conditions u mention rollback.seee the Connection class in jdbc API.normally its AtuoCommint true.so before starting transction setAutoCommit fasle.
    second question:
    in the saveButton action performed first check the textField.getText().equals("") for all the 3 textfields.if the condtions doesnt met popup optionpane.showdialog();
    if met just save it.
    3 rd question answer:
    this also same like first question.try to save in transaction.if anything happens wrong everything will be rollbacked.
    4th question:
    use unique in sql .u can set the 1 r more columns in table as unique key.
    for all these to work ur database shud support transactions....

  • JFileChooser question

    Hey Guys,
    My First post on the sun forums, so a big hello to you guys. I have a question in relation to best practice in querying something in one user interface, of another user interface. Suppose i have a class that consists on a TextField,JButton, and a JButton which opens a JFileChooser; i would like to return the value of the JTextField from the second GUI class to a calling gui class (gui1), once the OK button has been pressed. The second gui class consists of the following.
    package UserInterface;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    Class that allows for a local file to be chosen
    @author pthug
    public class ImageChooser extends JFrame {
    private JButton okButton;
    private JButton chooseFileButton;
    private JTextField locationTextField;
    private JPanel mainPanel;
    private JPanel locationPanel;
    private JFileChooser fc;
    private String address;
    //default constructor
    public ImageChooser() {
    super("Image Chooser");
    //set default size
    setSize(new Dimension(450,250));
    setResizable(false);
    //create components
    initComponents();
    //set layout - top to bottom
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
    locationPanel.setLayout(new FlowLayout());
    //add components to frame
    addComponents();
    //pak components
    pack();
    //centre frame on screen
    setLocationRelativeTo(null);
    //close frame as default operation
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    //add action listeners to components
    createActionListeners();
    //show frame
    setVisible(true);
    //*adds all components*
    *private void addComponents() {*
    *locationPanel.add(locationTextField);*
    *locationPanel.add(chooseFileButton);*
    *mainPanel.add(locationPanel);*
    *mainPanel.add(okButton);*
    *this.add(mainPanel);*
    *//*create the components for interface
    private void initComponents() {
    okButton = new JButton("OK");
    chooseFileButton = new JButton("...");
    locationTextField = new JTextField(50);
    mainPanel = new JPanel();
    locationPanel = new JPanel();
    fc = new JFileChooser();
    address = new String("");
    //create action listeners for components
    private void createActionListeners() {
    //open File Choose Dialog
    chooseFileButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == chooseFileButton) {
    int returnVal = fc.showOpenDialog(ImageChooser.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    locationTextField.setText(file.getPath());
    } else {
    System.out.println("Open command cancelled by user." + "\n");
    //ok button action listener
    okButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    address = locationTextField.getText();
    //some more methods that determine if a web address has been typed in the JTextField or whether a
    //local file has been chosen using the JFileChooser which has not been written yet
    //@param args
    public static void main(String[] args) {
    ImageChooser co = new ImageChooser();
    }and a call the class from a the first gui class as such
    GUI 1
    addImageItem.addActionListener(new ActionListener() {
                 @Override
                      public void actionPerformed(ActionEvent arg0) {
                           imageChooser = new ImageChooser();
    ... remaining source of class remove as its not necessary to the questionhow can i query when the ok button has been pressed on the second gui class, so that the first gui knows when to take the value from the JTextField. Would i just put a method in the second gui which is a boolean that holds true or false whether its ok to take the value from the JTextField and query it like such...
    //                       while(imageChooser.isStillOpen()) {
    //                       }Hope that makes sense.
    Regards,
    KevJ
    Edited by: KevJ on 10-Nov-2009 17:05

    Thank you for your reply bharath.bravo, that has solved my question. Which i did as such, i provided a method in the second GUI class to enable me to add an ActionListener to the OK button. As such
          * this method allows other classes to add their action listeners to
          * the OK Button
          * @param e Action Listener from another class
         public void addActionToOKButton(ActionListener e) {
              okButton.addActionListener(e);
         }     I then added a accessor method, to get the value from the textfield; which i've implemented it as such:
    imageChooser.addActionToOKButton(new ActionListener() {
                                  @Override
                                  public void actionPerformed(ActionEvent arg0) {
                                                                                                                    //use imageChooser accessor method to get the value from the text field
                                       imageLocation = imageChooser.getLocationTextField();
                                                                                                                    //DEBUG statement
                                       System.out.println("gui one recieved: " + imageLocation);
                                                                                                                    //get rid of imageChooser window
                                       imageChooser.dispose();
                                  }For the sake of clarity, in your first suggestion. You mentioned that i could implement the WindowListener Interface in the first gui, and add it as a Listener to the second gui. Would i do that like this, and what would be a prefferable way of doing this out of the two methods you suggested.
    public class GUI extends JFrame implements WindowListener
         @Override
         public void windowClosed(WindowEvent arg0) {
              // TODO Auto-generated method stub
              //get value of jTextField using its public accessor method          
    add window listener to second gui, from the first GUI
    imageChooser.addWindowListener(this);Regards,
    KevinJ
    Edited by: KevJ on 11-Nov-2009 14:38

  • JFileChooser Questions

    Hi,
    I have 2 questions concerning the use of JFileChooser:
    1. When you use "Details" option to see the details of the files; the "Modified" column seems to show the time in "United States" format even if the local regional setting is something else. Is this the default behavior of the JFileChooser or is there something that I can do to change that?
    2. It seems that you cannot just click on the column headers such as "Modified" to have the files sorted by that column like real Window's file chooser... Is that also the default behavior or is there something that I can do to change that?
    Thanks....

    you can read this
    http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html
    to know all the subtilities fo the JFileChooser

  • JFileChooser Question .... wo hoo!

    Hey there,
    I have a question regarding the JFileChooser class. I have managed to instantiate a file chooser and specify that it display directories only, I have also worked out how to get information when the "Attach" button (my custom button) or the "cancel" button is pressed. When the "Attach" button is pressed I return a file object that selects the user selected directory. I then print the directory to the standard output. Unfortunately the entire selection is not being printed, only the top level directory relevant to the selection is being printed. If you are familiar with JFileChooser then you will probably know what it looks like when it is instantiated. To refresh a couple of areas of significance to my program are the "Look in:" section and the "File Name:" section.
    I need my program to print the inforamtion in the "File Name:" section not the "Look in:" section as it is doing now. My code is as follows:
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    public class TestChooser extends JFrame
      public TestChooser()
        final JFileChooser fC = new JFileChooser(); //Final modifier needed
                                    //because this object is used in an  inner class.
        fC.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        JButton button1 = new JButton();
        button1.setText("Activate File Chooser");
        button1.setBounds(50, 50, 50, 50);
        button1.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            int returnVal = fC.showDialog(TestChooser.this, "Attach");
            if(returnVal == JFileChooser.APPROVE_OPTION)
              File curDirectY = fC.getCurrentDirectory();
              /* The "Look In:" Label information is being returned,
                 instead of the complete directory & folder details
                 contained in "File Name:". Note that File Name has the
                 keyMnemonic of underscore N.
              String str = curDirectY.toString();
              System.out.println("Of course the selected Directory is "+str);
        this.getContentPane().add(button1);
      public static void main(String args[])
        JFrame frame = new TestChooser();
        frame.setBounds(100, 100, 300, 200);
        frame.setVisible(true);
    }I have noticed that the "File Name:" section has a Key Mnemonic of N so maybe that can be used in the actionListener, I'm just not sure how. If anybody can help me with retrieving the information from the "File Name:" section as opposed to the "Look in:" section it will be greatly appreciated.
    Regards
    Davo

    <snip>
    File curDirectY = fC.getCurrentDirectory();The above method is the wrong method to call. It returns the directory that the JFileChooser itself is pointing at. It knows nothing about what file or directory may have been selected. Use the getSelectedFile() method instead.
    Jim S.

  • JFileChooser question regarding the order of the files in a folder

    I was hoping someone had a way around this issue I am having with the JFileChooser. I have a folder that has filenames in it like text1.txt, text2.txt, and so forth all the way up to text300.txt. When the filechooser shows these files it shows the order of them as:
    text1.txt
    text10.txt
    text11.txt
    text2.txt
    text20.txt
    text21.txt
    and so forth.
    How come it doesn't list them like they would be in a folder window like:
    text1.txt
    text2.txt
    text3.txt
    text150.txt
    text151.txt
    text299.txt
    text300.txt
    Actually I know why JFileChooser does it this way, it is because it sorts them as Strings without taking into account the number at the end of a similar string.
    Anyway, I was wondering if anyone had some ideas of how I could alter the JFileChooser to list the contents of a folder like this in the "right" order. Hopefully that made sense. :) Thanks.

    Thank u for ur reply.... actually the thing is mine's one of the pre-ordered iphones n it's reaching me by 2moro i think. so are the pre-ordered iphone's already activated? or m i in trouble if it's not activated out of the box (if i have to activate it myself). ?

  • Batch Process Export As and Save As JPEG Question?

    What is the method for creating scaled JPEGs from PNG files with batch processing (File | Batch Process...)?
    Application environment: Fireworks CS4.
    Using History panel, I manually captured instructions
    Modify | Transform | Numeric Transform (13%)
    Modify | Canvas | Fit Canvas
    File | Save As (JPEG)
    History panel's saved JavaScript file script:
    fw.getDocumentDOM().scaleSelection(0.11999999731779099, 0.11999999731779099, "autoTrimImages transformAttributes");
    fw.getDocumentDOM().setDocumentCanvasSizeToDocumentExtents(true);
    fw.saveDocumentAs(null, true);
    Running this sequence as a batch job requires manually selecting JPEG and "okaying"
    CS4 documentation for saveDocumentAs is defined with different argument list: fw.saveDocumentAs(document) .  CS4 documentation also has: fw.exportDocumentAs(document, fileURL, exportOptions) to export JPEG (80% quality).  CS4 feature File | Image Preview... | Export does not create a history record for guidance.  I cannot find an example of either instruction save a file to a local folder in JPEG format.  My objective is to add an additional batch step Rename (prefix) for the JPEG output, and script this a a batch process.

    Joyce,
    Thank you.  Your suggestion helped clear my mental log jam.
    Fireworks batch scripting seems to work in reverse.
    Using "Batch Process..." scripting interface 'Export' (as JPEG) option first, 'Rename' (add Prefix) option second, and then follow these by using the history panel's 2 previously saved steps (Numeric Transform, Fit Canvas), batch process now works.  PNG file (list) is saved in targeted folder as a reduced scale JPEG with a prefixed file name.
    Batch Process allows the entire newly defined command sequence to be saved (script.js).  Placing this (renamed) file into Firework's batch look-up directory for scripts (C:\Documents and Settings\account_name\Application Data\Adobe\Fireworks CS4\Commands) does not work.  The file name does not display in "Batch Process" window "Batch options:" Commands drop-down list.
    Batch Process only works by recreating the above steps each use.
    The new (JavaScript) file is 26 KB.  Is script file size limited in Fireworks "Batch options:" feature?

  • "Save as PDF" question

    I am saving SolidWorks drawings as PDF's. I have found that I can Save small drawings as PDF with no problem, But If I have a drawing that is a larger File size. The saved PDF file is a white sheet. Is there any idea why this is happening? Below is the specs of SW's and Adobe.
    Thanks.
    Solid Works- 2011 SP. 2
    Adobe Standard- 9.0

    The application is using Acrobat to create the PDF. I save drawings with file sizes around 15MB to 20MB on the normal bases. Once in a while i need to save files upwards of 40MB to 50MB. This is were I have the problem of the file not saving correctly. These drawings have alot of graphics. Could that cause problems with Acrobat or would it be the SolidWorks application? I checked with Solidworks Tech. Support and they said its not a problem on there end. Very frustrating....

  • Remote Desktop - Cmd+D - save without closing question

    I'm trying to write a script that will allow me to quit an application (SketchBookExpress) without saving changes.  I'm having trouble with the syntax for the "Don't Save" (cmd+d).  The script runs but stops at the on screen Save/Canel/Don't Save dialog box. 
    What I have tried is the following:
    osascript -e 'tell application "SketchBookExpress" to activate';
    osascript -e 'tell application "SketchBookExpress" to quit';
    osascript -e 'tell application "System Events" to delay 0.5';
    osascript -e 'tell application "System Events" to keystroke "d" using {command down}';
    And I've tried:
    osascript -e 'tell application "SketchBookExpress" to quit';
    osascript -e 'tell application "System Events" to delay 0.5';
    osascript -e 'tell application "System Events" to key down command';
    osascript -e 'tell application "System Events" to keystroke "d"';
    And, I've also tried:
    osascript -e 'tell application "SketchBookExpress" to quit';
    osascript -e 'tell application "System Events" to delay 0.5';
    osascript -e 'tell application "System Events" to to keystroke "d" using {command}';
    I'm very new to Remote Desktop and AppleScript and would appreciate any help you can provide about how to close an app without saving it.
    Thanks.

    I think you need to turn this on its head.
    SketchBook Express is not scriptable, so you can't use the 'normal' method, which would be:
    tell application "SketchBook Express" to quit saving no
    The problem with your approach is that AppleScript is serial - each command is executed in turn, so it's waiting for the app to quit before executing the next command (unless you run all these commands in parallel, but that's a different issue.
    However, there's a simpler solution to your problem:
    killall SketchBookExpress
    This sends the Kill command to the app, quitting it, bypassing the whole 'Save changes?' process.
    This is a standard shell command, so you don't need AppleScript (or osascript) to run it. If you do want to wrap this in a larger script, just use 'do shell script':
    do shell script "killall SketchBookExpress"

  • Save For Web Question

    How do I get photoshop to stop adding hyphens to file names when I
    save to web

    I find it convient to use this option to save png, gif and jpg for
    local powerpoint use and I have mutiple old macros in these Powerpoint
    that require certain file names. I am forced to remove the hyphens
    since rewrtting all the macros are a bit of a pain
    [newsreader autoquote deleted by forum host]

  • Save / Restore State Question

    When writing a custom component, does one need to save/restore the state of facets and children. Or is this done automatically?
    Thanks,
    Ryan

    you don't need to. Its taken care of by JSF.
    -Jayashri

  • Calendar "save as pdf" question

    When saving a calendar as a pdf, there doesn't seem to be any pdf quality settings for saving the calendar. I'm wondering because if I take that pdf file to a printer, is the file of lesser quality than if I uploaded from iPhoto to Apple for printing. So, when you use the File>Print>Save as PDF command, are you getting a highly compressed file or a high quality file?

    FWIW I also ran a test and compared three versions of the pdf file.
    1 - the one iPhoto creates in the invisible HD/private/var/tmp/folders.501/Temporaryitems/iPhoto file
    2 - from the Preview mode
    3 - from the Print to PDF mode
    All three were identical in size.
    Do you Twango?
    TIP: For insurance against the iPhoto database corruption that many users have experienced I recommend making a backup copy of the Library6.iPhoto database file and keep it current. If problems crop up where iPhoto suddenly can't see any photos or thinks there are no photos in the library, replacing the working Library6.iPhoto file with the backup will often get the library back. By keeping it current I mean backup after each import and/or any serious editing or work on books, slideshows, calendars, cards, etc. That insures that if a problem pops up and you do need to replace the database file, you'll retain all those efforts. It doesn't take long to make the backup and it's good insurance.

  • Save as Project question

    My templete has a midi track with a drum kit. In the new song I have deleted this track and it's regions but when I save the newly named song as a project it still wants to save the drum kit and it's regions.
    How do I stop this?
    BP

    What I would do before saving it again as a template is to go to the audio window, delete all files there, go to the arrange widow , and delete all sequences and regions. Then choose the Save as Template option, again, and name it the same way to replace the old one.

  • I get an error message in itunes when I try and save my security question answers.  This is stopping me from downloading music.  What could be the problem?

    I try and buy a song in itunes.  But, It keeps taking me to the security questions in which it won't accept.  Thanks

    Also I now can`t access any of my itunes library and am concerned that if I remove it from my computer I will lose everything as I have no option of accessing and therefore backing anything up. Any ideas?

Maybe you are looking for

  • Safari 3.2.1 on mac fails to play embedded audio content.

    my homepage, http://bloodnok.net/ has an embedded audio snippet. the audio snippet is loaded using an <object> tag. the page is xhtml transitional (don't want to be strict) & validates on the w3c site. when i visit the site with firefox or opera from

  • Kernal panic (ethernet), USB mouse prob, kb backlight failed

    Hey all: Sometimes when I remove the ethernet cable from my PB I get a kernal panic message. It has also happened when I move my PB when the ethernet cable is connected, as well as some other times that are just plain random. Additionally, my wireles

  • High speed and Low Speed CAN

    Hi This is my first time to use CAN. I have LabVIEW  2010 and  LabVIEW FPGA I have NI 3110 Dual-Core Industrial Controller with Windows OS, NI 9157, NI 9852 CAN Low Speed Module and NI 9853 CAN High Speed Module to be used to monitor the CAN messages

  • How is the Cosine function applied to O-cluster?

    One of the distance functions used in O-cluster is the Cosine function. I know how the Euclidean function works but don't understand how Cosine function is applied to O-cluser algorithm. I would like to know how the cosine function f(x) = a*cos(bx +

  • Titles in iPhoto?

    I only want a version of iPhoto on my iPad so that I can see the organization of the photos, in albums, folders, and to be able to see the titles and descriptions, especailly when I do a slide show. Is this possible with iPhoto on the iPad? I don't w