Filefilter for jfilechooser --Confused-

JFileChooser JFC=new JFileChooser();
JFC.setFileFilter(new ExeFileFilter());
class ExeFileFilter implements FileFilter
{          public boolean accept(File TheFile)
          if(TheFile.getName().endsWith("exe"))
          return true;
     return false;
}the above code doesnt work, tried several possibilities
can anyone help me??

what i want is that the JFilechooser show only exe
file..
helpdid you read the examples in JFilechooser Tutorial?
all you have to do is modify to it.
here's the code:
ImageFilter Class
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;
public class ImageFilter extends FileFilter {
    //Accept all directories and all gif, jpg, tiff, or png files.
    public boolean accept(File f) {
        if (f.isDirectory()) {
            return true;
        String extension = Utils.getExtension(f);
        if (extension != null) {
            if (extension.equals(Utils.tiff) ||
                extension.equals(Utils.tif) ||
                extension.equals(Utils.gif) ||
                extension.equals(Utils.jpeg) ||
                extension.equals(Utils.jpg) ||
                extension.equals(Utils.png)) {
                    return true;
            } else {
                return false;
        return false;
    //The description of this filter
    public String getDescription() {
        return "Just Images";
}Utils Class
import java.io.File;
import javax.swing.ImageIcon;
/* Utils.java is used by FileChooserDemo2.java. */
public class Utils {
    public final static String jpeg = "jpeg";
    public final static String jpg = "jpg";
    public final static String gif = "gif";
    public final static String tiff = "tiff";
    public final static String tif = "tif";
    public final static String png = "png";
     * Get the extension of a file.
    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');
        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        return ext;
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = Utils.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
}

Similar Messages

  • How can I set a default file for JFileChooser

    Hi. I am developing a p2p chat application and I have to unrelated questions.
    1. How can I set a default file name for JFileChooser, to save a completly new file?
    2. I have a JTextArea that I append recieved messages. But when a message is appended, the whole desktop screen refreshes. How can I prevent that?
    Hope I was clear. Thanks in advance.

    Thank you for the first answer, it solved my problem. Here is the code for 2nd question, I've trimmed it a lot, hope I didn't cut off any critical code
    public class ConversationWindow extends JFrame implements KeyListener,MessageArrivedListener,ActionListener,IOnlineUsrComp{
         private TextArea incomingArea;
         private Conversation conversation;
         private JTextField outgoingField;
         private JScrollPane incomingTextScroller;
         private String userName;
         private JButton inviteButton;
         private JButton sendFileButton;
         private JFileChooser fileChooser;
         private FontMetrics fontMetrics;
         private HashMap<String, String> onlineUserMap;
         public void MessageArrived(MessageArrivedEvent e) {
              showMessage(e.getArrivedMessage());
         public ConversationWindow(Conversation conversation)
              this.conversation=conversation;
              userName=User.getInstance().getUserName();
              sendFileButton=new JButton("Dosya G�nder");
              sendFileButton.addActionListener(this);
              inviteButton=new JButton("Davet et");
              inviteButton.addActionListener(this);
              incomingArea=new TextArea();
              incomingArea.setEditable(false);
              incomingArea.setFont(new Font("Verdana",Font.PLAIN,12));
              fontMetrics =incomingArea.getFontMetrics(incomingArea.getFont());
              incomingArea.setPreferredSize(new Dimension(300,300));
              outgoingField=new JTextField();
              outgoingField.addKeyListener(this);
              incomingTextScroller=new JScrollPane(incomingArea);          
              JPanel panel=new JPanel();
              panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS));
              panel.add(inviteButton);
              panel.add(sendFileButton);
              panel.add(incomingTextScroller);
              panel.add(outgoingField);
              add(panel);
              pack();
              setTitle("Ki&#351;iler:");
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              setLocationRelativeTo(null);
              addWindowListener(new CloseAdapter());
         //Sends the message to other end
         public void keyPressed(KeyEvent e) {
              if(e.getKeyCode()==KeyEvent.VK_ENTER && e.getSource()==outgoingField)
                   String message=outgoingField.getText();
                   if(message.equals("")) return;
                   showMessage(userName+": "+message);
                   conversation.sendMessages(userName+": "+message);
                   outgoingField.setText("");     
         //Displays the recieved message
         public void showMessage(String message)
              if(fontMetrics.stringWidth(message)>incomingArea.getWidth())
                   int mid=message.length()/2;
                   StringBuilder sbld=new StringBuilder(message);
                   for(;mid<message.length();mid++)
                        if(message.charAt(mid)==' ')
                             sbld.setCharAt(mid, '\n');
                             message=sbld.toString();
                             break;
              incomingArea.append("\n"+message);
    }

  • Is there any way to get preview of word,excel as accesory for JFileChooser?

    i want to set an accessory for jfilechooser so that i can preview documents file or any media files using the setAccessory method of JFileChooser.
    Will it can be done by Runtime.getRuntime.exec() as an win32 api method so that it can open the file in the accesory of jfilechooser or in jFrame instead of another window.
    Plz anybody have any idea's.

    That's correct...itune's app store will always prompt you to update. Hopefully Apple will change this policy!

  • Custom DE for easily confused / computer illiterate people

    Hi!
    I'm about to install a DE mainly for easily confused / computer illiterate people on a machine.
    What comes to my mind is:
    - Big buttons for "Internet", "Office", "Files & Multimedia", Advanced
    - Browser on one desktop (open all the time)
    - Office writer on another desktop (open all the time)
    - File manager + mediaplayer on a Desktop (open all the time)
    - Empty Desktop with Icons for GIMP etc. on last Desktop ("Advanced")
    - No window decorations, as few "unnecessary" GUI elements as possible
    I guess the simplest way to do something like this should be using a tiling window manager that takes care of everything being on the right Desktop (/ in the right group) and writing some small scripts that see to it that the "main programs" are open & running... right?
    Any ideas / hints on...
    - Which wm to use (haven't used a tiling WM yet... which one's easiest for that scenario? Awesome?)
    - What applications to use? (Kazehakase, Abiword, Thunar, Whaawmp, Tuxpaint...?)
    - How to get started? Anyone got useful tiling WM configs / scripts that are part of something sort of similar?
    Thanks!

    I thought about a tiling WM, because managing, resizing, minimizing windows can be sort of tricky. I'm talking about things like:
    - "Where did it go?"
    - "I can't see both folders at once!" (<= and this one's for "advanced users" - really.)
    - "Why is there not enough place to see the stuff?"
    You ever seen someone click on the "_" and panic because his letter was gone? Things like that. Or dragging the panel to the left screen edge and not managing to get it back. Yes, there's people that pull the plug to "reboot" if they accidentally opened a program they didn't want to open and they can't see an icon+text for the program they just used any more.
    Of course I'd have to configure the tiling WM in an easy to use way. 3-4 sets of programs that are automatically tiled. One permanently visible button to reach each set/Desktop, nothing that can be messed up.
    ( And KDE gives even me the creeps - keep in mind that you're used to it and know what you're doing. Being able to "drag everything around, make floating things take up all the space and get lost in huge menus with many many options" isn't really what I'm looking for )
    edit:
    If this person is really bad at using computers, there is no app or WM that will make that go away.
    Yes, but
    - if everything is a bit more obvious
    - there aren't so many choices of what to do
    ... I guess it's a big difference non the less. Most of those people I watched were OK as long as they had the program they wanted to use on the screen, knew their 3-10 important buttons and managed, not to click anything that opens an unfamiliar window.
    Also: I already had some people try gnome. Biggest problems really were maximizing windows (they don't do it, they work with them the way the spawn and once they accidentally un-maximized it, it stays small), loosing windows (behind others, minimized) and dragging the panel to the wrong place.
    Last edited by whoops (2009-11-14 13:40:31)

  • "Skype for business" Confusing meeting invitation

    When I create a new online Meeting in Outlook Calendar with the Skype for Business client , it Automatically set meeting location as "Skype" and a url to click to "Join Skype Meeting". This is very confusing for
    both internal and external users. People saying that they don't have Skype installed on their computers and don't have a Skype account. External users asks if we can host the Meeting on their GoToMeeting solution instead. 
    I hope there is a possibility to change the template or that Microsoft comes With a hotfix for this. The best would be if we could modify the text. If not, at least release a quick fix that adds "business" in the Location and "Join Skype
    Meeting"
    At the moment we have to manually change the location to Lync Meeting, and the url to "Join Lync Meeting" like it was before.
    This is very frustrating

    Hi,
    Agree with ANthony Caragol.
    I test the issue on my Lync environment, even I return the Skype For Business UI back to Lync UI, then restart Lync and Outlook, the Lync Meeting Add-in still show "Skype Meeting Add-in for Microsoft Office 2013".
    So now the workaround is to change it to "Join Lync meeting" manually.
    Best Regards,
    Eason Huang
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact [email protected]
    Eason Huang
    TechNet Community Support

  • Need help for JFileChooser

    Hi,
    I need help on this one. I have a filechooser class which extended from JFileChooser class. Every thing works fine except this: I want to by hiting the "Enter" key to save the files. The "Enter" key works only when the focus is in the file name text field now, I want it to work when the focus is in the directory area, the file list area and the file type area as well. I try to add the KeyListener but how can I get hold of the component of the three areas of file chooser? I tried to add the KeyListener as Accessory, it didn't work either. Some one please help me.

    Try this to let your components react to ActionEvents
    comp.addActionListener(new  WhatIWantToDo());
    // WhatIWantToDo is the inner class.
    // Let it do what you want to be the reaction
    class WhatIWantToDo implements ActionListener {
    public void actionPerformed(ActionEvent event) {
    //  code on what you want to do
    }Or working without an inner class try this
    comp.addActionListener(new ActionListener() {
    // the event handling
    public void actionPerformed(ActionEvent event) {
    // your code for behavior
    // e.g. System.out.println("There is a reaction");
    // or specify a special named component as c1
    Object source = event.getSource();
    if (source == c1) doSomething();
    else if (source == c2) doOtherThings();
    });Hope this is of help for what you want. Else let me know.

  • FileFilter for executable files

    I'm trying to make a FileFilter that only accepts executable files and directories. My attempt is shown below:
        public boolean accept(File f)
            if(f.isDirectory())
                return true;
            SecurityManager sm = new SecurityManager();
            try
                System.out.println(f.getPath());
                sm.checkExec(f.getPath());
            } catch (SecurityException e) {
                return false;
            return true;
        }This isn't returning anything but directories. It also strikes me as odd that the SecurityManager works by throwing exceptions, when it isn't really exceptional to have a file not be executable.
    Any help here would be appreciated.

    I wanted something that would work on any system. I figured that this functionality should exist simply because it is useful. As for the argument that it is too OS specific, I disagree. Every developed OS has some means for determining if a file is an executable program. Just as the Graphics package is supported on multiple systems despite different implementations, I believe that filetype identification could be done in the JREs.
    But it looks like it isn't done. That appears to be the answer to my question.

  • Generating virtual files for JFileChooser by implementing FileSystemView

    Hello,
    I'd like to display in a file hierarchy using JFileChooser component of data that I'm fetching from the database. From what I read thus far, I'll need to implement the FileSystemView and FileView abstract classes to generate virtual files on the client. There was also a reported bug for sdk 1.4.1_01 stating that subdirectories could not be viewed when running the JFileChooser. Does anyone know if this bug has been fixed in 1.4.1_02, and could anyone post some sample code how to implement these classes?
    Thanks a lot,
    Ariela

    Hello,
    I'd like to display in a file hierarchy using JFileChooser component of data that I'm fetching from the database. From what I read thus far, I'll need to implement the FileSystemView and FileView abstract classes to generate virtual files on the client. There was also a reported bug for sdk 1.4.1_01 stating that subdirectories could not be viewed when running the JFileChooser. Does anyone know if this bug has been fixed in 1.4.1_02, and could anyone post some sample code how to implement these classes?
    Thanks a lot,
    Ariela

  • What pattern is followed when using FileFilter for filtering files ?

    Hi All,
    FileFilter is used to filter files according to the condition specified.
    for example the code is
    FileFilter fileFilter = new FileFilter(){
    public boolean accept(File inFile) {
    // To return whether it is a file
    return inFile.isFile();
    // To return whether it ends with any extension.
    // for example ends with .txt
    // return inName.endsWith("txt");
    File[] files = file.listFiles(fileFilter);
    Here FileFilter is an interface.File is a class. What pattern is followed in this operation ? does it follows - similar to any design pattern in Java ? this implementation is similar to adding an ActionListener(like an Inner Class) to a button.
    for example
    Button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    Thanks,
    J.Kathir

    I am using a FileFilter with the following extension "*.doc". The
    getDescription() method for that extension returns "Microsoft Word
    Document", which is what gets displayed in the "Files of Type"
    dropdown. My problem is that if the user enter a wildcard (*) in the
    "File Name" field and hit enter, it changes the "Files of Type" drop
    down to that as well.
    How do you prevent the "Files of Type" selection from changing when
    using wildcard?

  • Active FileFilter in JFileChooser

    Ok, here is my problem:
    I successfully installed 2 TextFilters to my JFileChooser. But unfortunately when i open the JFileChooser Window only the last added FileFilter is active...But i want to start this window with the common file filter (*.*). So how can i set the active FileFilter from beginning?
    here is my Code:
                            fileChooser = new JFileChooser();
                   FileView fv = new ImageFileView();
                   fileChooser.setFileView(fv);
                   fileChooser.setFileFilter(new MyFileFilter(".pdf","Adobe Acrobat files (*.pdf)"));
                   fileChooser.setFileFilter(new MyFileFilter(".rtf","Rich Text Format files (*.rtf)"));
                   fileChooser.showOpenDialog(this);

    i know how to add fileFilter to my JFileChooser...and
    i read the FM!I figured this out in 2 minutes. Was this really so hard?
    private static void JFileChooserTest() {
              JFileChooser chooser = new JFileChooser();
              FileFilter o_filter = chooser.getFileFilter();
              FileExtensionFilter filter = new FileExtensionFilter.HTMLFilter();
              FileExtensionFilter filter2 = new FileExtensionFilter.RTFFilter();
              FileExtensionFilter filter3 = new FileExtensionFilter.TextFilter();
              chooser.addChoosableFileFilter(filter);
              chooser.addChoosableFileFilter(filter2);
              chooser.addChoosableFileFilter(filter3);
              chooser.setFileFilter(o_filter);
              chooser.showOpenDialog(null);
         }

  • L&F for JFileChooser

    When I show an open file dialog, its L&F is set back to the windows default. The components inside of it still have the Java L&F but the dialog itself is still windows. I didn't find a JFileChooser.setDefaultLookAndFeelDecorated() method :-). Please help.
    Regards,
    Igor

    The method is rather JDialog.setDefaultLookAndFeelDecorated(true)
    ICE

  • Creating index for book - Confused...

    So I have a 500+ page book in multiple documents all within a Book.indb. Very nice.
    I'm a little confused about how to build an index, though. It seems the only way is to manually go to each and every instance of a word or phrase and add it as a reference.
    I was just given a list of names, places, etc. that the client requires to be indexed. Is there any way I can just add these names, places, etc. by hand in the Index panel and have InDesign search the entire book and create the page number references itself?
    I tried this AddIndexReferencesFromList.jsx, but it doesn't check the entire book.

    Check out Michael Murphy's
    The InDesigner Blog. He has some video podcasts regarding long documents, and indexing, that you may find useful. Episode 36 "tackles the feature that is the bane of many an InDesign users existence: Indexing."
    If I recall the answer correctly, it is: Indexing is labor intensive and there is not an automatic way to add entries.
    It has been a while since I looked at it, though.
    HTH
    -mt

  • I have a Mac os x 10.7.4 which has Java 32 and 64 bit installed.  Am unable to deposit to bank online getting a message stating I need Java 32 bit for Mac, confused???

    I just got a MAC OS X 10.7.4 which has Java 32 and 64 bit installed.  Am unable to make deposits on line.  I get a msg stating it appears I am using 64 bit java and I need 32 bit java for MAC. I have changed order of java in preferences but it does not make a difference.  Suggestions?

    MadMAC0 posted at https://discussions.apple.com/message/20107182?ac_cid=tw123456#20107182 that:
    Apple has posted (10/22/12) the approved solution for restoring the Java 6 plug-in:
    Java for OS X 2012-006: How to re-enable the Apple-provided Java SE 6 applet plug-in and Web Start functionality.

  • Apply FileFilter for FileReference Download file

    I want to apply particular File Filter for FileReference
    class when i am downloading file.
    When i download my file it should be save in XML format only.
    How can i do this?
    Thanks,
    Nirav

    Hi Bonnie,
    when using download:
    http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference .html?#download()
    2038 IOError would be returned - at least as far as I can tell - if server returns:
    HTTP/1.1 404 Not Found
    status code that error would be thrown and then dispatched (but it won't contains 404 specific information - instead some general IO error for server url will be provided). So add IOErrorEvent.IO_ERROR to your FileReference instance - that is something you could try,
    hth,
    kind regards,
    Peter

  • Getting current directory for JFileChooser

    I'm trying to construct a JFileChooser that uses the current directory as its view (and not the default Windows "My Documents" directory path). How can I get the current directory path? File definately doesn't have anything, Toolkit neither.

    I had the same exact question a while ago. The solution is quite simple.
    JFileChooser j = new JFileChooser(".");

Maybe you are looking for

  • How to get my apple I'd off a macbook pro with having to giv my I'd and password away

    I had sold my macbook pro to someone and they say they can't update the computer without my I'd, the problem I am confused about Is when ii gave him the computer I already restore the computer to not need my apple I'd, is there anything he can do wit

  • BPC 7.5 : Error in deleting member from dimension

    Hi All In BPC 7.5, I have created earlier one member "F_P/L"in Flow Dimension and tested some data. Now I want to delete the member "F_P/L" from the Flow Dimension and while processing it, I am getting following error :                    " Dimension

  • Log and transfer question

    OK I was wondering if when I import AVCHD from my hard drive if the original files would be damaged at or removed at all. I just had a slight issue, and was wondering if that would be a problem. Any advice is appreciated. Thanks!

  • Horizontally and vertically growing matrix

    Hi, I'm using forms6i. I'll explain my scenarion I have one item(not forms item), which can be packed in different ways and different levels like , item1 has 3 levels Level1 Level2 Level3and each level has different packs saly level1 -->pack1,pack2 l

  • How to add binding effect in indesign?

    How can you add binding effects to an InDesign document so it looks like a book or notebook when converted to a pdf? Below is an example http://blogs.adobe.com/indesigndocs/files/indesigndocs/SWF.jpg