JFileChooser in mode FILES_ONLY

Hi,
I've a little problem with the JFileChooser.
I open a JFileChooser in FILES_ONLY mode with a default filename.
The default filename is displayed fine but when I click on a directory name my filename is overwritten by the selected directory name.
Because I can only select files (Files_Only) this is not normal and not consistant with other Windows applications.
I work with SDK 1.3.1 on a windows machine.
Below you can find my code.
Is there a workaround for this ?
Rgds,
Piet
      String originalFileName = "MyFile.doc";
      JFileChooser fc = new JFileChooser();
       fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
       fc.setSelectedFile(new java.io.File(originalFileName));
       int returnVal = fc.showOpenDialog(this);

I am running java 1.4.2 and the code that you have posted worked exactly like you wanted. I copy & pasted in to my ide, replaced fc.showOpenDialog(this) with fc.showOpenDialog(new JFrame()) and ran it. The displayed file "MyFile.doc" did not change when I browsed to different directories.
I tried both the Metal and Windows plaf's, both worked.
This probably doesn't help you on 1.3.1, but at least you know it was fixed at some point.
Josh Castagno
http://www.jdc-software.com

Similar Messages

  • JFileChooser, how can you allow the user to select MORE than 1 file?

    Hello everyone.
    I want to allow the user to select multiple files from a directory, not just 1, but not just the whole directory.
    Currently I see these 2 options from looking at the sun's JFileChooser demo:
    //Create a file chooser
            fc = new JFileChooser();
            //Uncomment one of the following lines to try a different
            //file selection mode.  The first allows just directories
            //to be selected (and, at least in the Java look and feel,
            //shown).  The second allows both files and directories
            //to be selected.  If you leave these lines commented out,
            //then the default mode (FILES_ONLY) will be used.
            //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);but both don't allow the selection of more than 1 file.
    When I say, select more than 1 file I mean the user can hold in SHIFT or CTRL and select files.
    Any ideas how to do this?
    Thanks!

    http://java.sun.com/javase/6/docs/api/javax/swing/JFileChooser.html#setMultiSelectionEnabled(boolean)
    Cheers,
    Laird

  • Combining File Chooser and this MP3 class

    Hello all,
    I was curious if anyone could help me figure out how to get a file to actually load once it is used with this code.
    I'm unfamiliar with how it works and I was hoping for an explanation on it.
    I wasn't sure if I had to have the program recgonize that I would like to load a mp3 or if it just would load it automatically...
    Essentially, I want to be able to load a mp3 if I use the file chooser.
    I can try to clarify my question more if anyone should need it.
    Thank you
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class List extends JPanel
                                 implements ActionListener {
        static private final String newline = "\n";
        JButton openButton, saveButton;
        JTextArea log;
        JFileChooser fc;
        public List() {
            super(new BorderLayout());
            //Create the log first, because the action listeners
            //need to refer to it.
            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
            fc = new JFileChooser();
            //Uncomment one of the following lines to try a different
            //file selection mode.  The first allows just directories
            //to be selected (and, at least in the Java look and feel,
            //shown).  The second allows both files and directories
            //to be selected.  If you leave these lines commented out,
            //then the default mode (FILES_ONLY) will be used.
            //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
           // fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            //Create the open button.  We use the image from the JLF
            //Graphics Repository (but we extracted it from the jar).
            openButton = new JButton("Open a File...",
                                     createImageIcon("images/Open16.gif"));
            openButton.addActionListener(this);
            //Create the save button.  We use the image from the JLF
            //Graphics Repository (but we extracted it from the jar).
            saveButton = new JButton("Save a File...",
                                     createImageIcon("images/Save16.gif"));
            saveButton.addActionListener(this);
            //For layout purposes, put the buttons in a separate panel
            JPanel buttonPanel = new JPanel(); //use FlowLayout
            buttonPanel.add(openButton);
            buttonPanel.add(saveButton);
            //Add the buttons and the log to this panel.
            add(buttonPanel, BorderLayout.PAGE_START);
            add(logScrollPane, BorderLayout.CENTER);
        public void actionPerformed(ActionEvent e) {
            //Handle open button action.
            if (e.getSource() == openButton) {
                int returnVal = fc.showOpenDialog(List.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);
                log.setCaretPosition(log.getDocument().getLength());
            //Handle save button action.
            } else if (e.getSource() == saveButton) {
                int returnVal = fc.showSaveDialog(List.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);
                log.setCaretPosition(log.getDocument().getLength());
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = List.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("FileChooserDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new List();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }The mp3 class that I've been playing around with...
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import javazoom.jl.player.Player;
    public class MP3 {
        private String filename;
        private Player player;
        // constructor that takes the name of an MP3 file
        public MP3(String filename) {
            this.filename = filename;
        public void close() { if (player != null) player.close(); }
        // play the MP3 file to the sound card
        public void play() {
            try {
                FileInputStream fis = new FileInputStream(filename);
                BufferedInputStream bis = new BufferedInputStream(fis);
                player = new Player(bis);
            catch (Exception e) {
                System.out.println("Problem playing file " + filename);
                System.out.println(e);
            // run in new thread to play in background
            new Thread() {
                public void run() {
                    try { player.play(); }
                    catch (Exception e) { System.out.println(e); }
            }.start();
    // test client
        public static void main(String[] args) {
            String filename = "C:\\FP\\1.mp3";
            MP3 mp3 = new MP3(filename);
            mp3.play();
    }

    Thanks for the link
    I've been looking over the sections and still confused with the code.
    It's obvious that I have to do something with this portion of the code:
    public void actionPerformed(ActionEvent e) {
        //Handle open button action.
        if (e.getSource() == openButton) {
            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);
    }I'm just not sure what.

  • Why does is not show the radio buttons

    I want to display the buttons in a row then radio button in a row under the button and then log scroll pane under the radio buttons. This is my code:
            //Add the buttons and the log to this panel.
            add(buttonPanel, BorderLayout.PAGE_START);
            add(radioPanel, BorderLayout.CENTER);
            add(logScrollPane, BorderLayout.CENTER);When i run it it display the buttons and the logsrollpane. Why does it not display the radio buttons?

    Thanks guys.
    This is my problem. We have a big system that produce lots of log files and the software testers have to manually have to go through the logs file and look for a certain XML tags in the log file.
    What I want to do is help the software testers my developing a small tool that will allow them to open a log file and then click on a radio button corresponding to a xml tags that they are looking for and automatically highlight the tags in the file in yellow color .
    I am not sure how feasible this is and I am stuck.
    This is what I have done so far.
    Can you please guys help me go forward.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class FileChooserDemo extends JPanel
                                 implements ActionListener {
        static private final String newline = "\n";
        JButton openButton;
        JButton clearButton;
        JTextArea log;
        JFileChooser fc;
        // Radio Buttons
        static String em01 = "EM01";
        static String em07 = "EM07";
        /*static String dogString = "Dog";
        static String rabbitString = "Rabbit";
        static String pigString = "Pig";*/
        public FileChooserDemo() {
            super(new BorderLayout());
            //Create the radio buttons.
            JRadioButton em01Button = new JRadioButton(em01);
            em01Button.setMnemonic(KeyEvent.VK_B);
            em01Button.setActionCommand(em01);
            em01Button.setSelected(true);
            JRadioButton em07Button = new JRadioButton(em07);
            em07Button.setMnemonic(KeyEvent.VK_C);
            em07Button.setActionCommand(em07);
            //Group the radio buttons.
            ButtonGroup group = new ButtonGroup();
            group.add(em01Button);
            group.add(em07Button);
            //Register a listener for the radio buttons.
            em01Button.addActionListener(this);
            em07Button.addActionListener(this);
            //Put the radio buttons in a column in a panel.
            JPanel radioPanel = new JPanel(new GridLayout(0, 1));
            radioPanel.add(em01Button);
            radioPanel.add(em07Button);       
            //Create the log first, because the action listeners
            //need to refer to it.
            log = new JTextArea(40,60);
            log.setMargin(new Insets(5,5,5,5));
            log.setEditable(false);
            JScrollPane logScrollPane = new JScrollPane(log);
            //Create a file chooser
            fc = new JFileChooser();
            //Uncomment one of the following lines to try a different
            //file selection mode.  The first allows just directories
            //to be selected (and, at least in the Java look and feel,
            //shown).  The second allows both files and directories
            //to be selected.  If you leave these lines commented out,
            //then the default mode (FILES_ONLY) will be used.
            //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            //Create the open button.  We use the image from the JLF
            //Graphics Repository (but we extracted it from the jar).
            openButton = new JButton("Open File");
            openButton.addActionListener(this);
            //Create the save button.  We use the image from the JLF
            //Graphics Repository (but we extracted it from the jar).
            clearButton = new JButton("Clear Text Area");
            clearButton.addActionListener(this);
            //For layout purposes, put the buttons in a separate panel
            JPanel buttonPanel = new JPanel(); //use FlowLayout
            buttonPanel.add(openButton);
            buttonPanel.add(clearButton);
            //Add the buttons and the log to this panel.
            add(buttonPanel, BorderLayout.PAGE_START);
            add(radioPanel, BorderLayout.LINE_START);
            add(logScrollPane, BorderLayout.CENTER);
        public void actionPerformed(ActionEvent e) {
            //Handle open button action.
            if (e.getSource() == openButton) {
                int returnVal = fc.showOpenDialog(FileChooserDemo.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                     log.setText("");
                    File file = fc.getSelectedFile();
                    try{
                         BufferedReader in = new BufferedReader(new FileReader(file));
                             String data;
                             while ((data = in.readLine()) != null) {
                                  log.append(data + newline);
                    }catch(IOException ioe){
                log.setCaretPosition(log.getDocument().getLength());
            //Handle save button action.
            }else if (e.getSource() == clearButton) {
                  log.setText("");
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("PROGRESS Message Viewer");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new FileChooserDemo();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

  • Child window closing problem

    hello guys
    i have a main GUI frame and one button on that fires another frame with few graphs. i have an exit button the child one that needs to close that window and return to main one but that button is not working.
    i have tried almost everything so far viz. dispose(), DISPOSE_ON_CLOSE, ChildFrame.this.dispose(), setVisible(false),,,,,, but nothing is working.
    please please help .....
    thanks a lot

    ok.. its a bit longer to read but i m doin it
    ################ child class ###################
              /* Split pane to view simulation results*/
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.AbstractButton;
    import javax.swing.ImageIcon;
    public class GraphPane extends JFrame implements ActionListener {
         private JPanel base,graphic;
         private JButton first,second,third,fourth,fifth,viewer,quit;
         private JTextField firstT,secondT,thirdT,fourthT,fifthT;
         private JSplitPane hPane;
         private TitledBorder title;
         private JFileChooser fc;
         //mode constants
         private final String FIMB="fimB graphs";
         private final String FIME="fimE graphs";
         private final String FIMBOTH="Co-ordinated graphs";
         //mode flag
         private String modus=FIMBOTH;
         // arrays to hold data of the simulation(s)
         private int[] reader1=new int[75];
         private int[] reader2=new int[75];
         private int[] reader3=new int[75];
         private int[] reader4=new int[75];
         private int[] reader5=new int[75];
         // arrays to supply data
         private int[] supply1=new int[25];
         private int[] supply2=new int[25];
         private int[] supply3=new int[25];
         private int[] supply4=new int[25];
         private int[] supply5=new int[25];
         // comboBox to choose viewing option
         private JComboBox selector;
         //change determiner
         private boolean isChange;
         //setting up gridbag layout
         GridBagLayout gridbag;
        GridBagConstraints c;
          public Component createViewcom() {
               //put a relevant image on buttons
               ImageIcon opnerIcon = createImageIcon("images/opener.gif");
               //create a file chooser
              fc=new JFileChooser() ;
              fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              fc.setFileFilter(new NewFileFilter());
              // create the mode chooser
              selector=new JComboBox();
              selector.addItem(FIMBOTH);
              selector.addItem(FIMB);
              selector.addItem(FIME);
              selector.setFocusable(false);
              //adding item listener
              ModeListener modeListener=new ModeListener();
              selector.addItemListener(modeListener);
              selector.revalidate();
               //selection buttons
               first=new JButton("Simulation_1",opnerIcon);
               first.setHorizontalTextPosition(AbstractButton.LEFT);
               first.setForeground(Color.red);
               first.setFocusable(false);
              first.addActionListener(new ButtonAction1());
               second=new JButton("Simulation_2",opnerIcon);
               second.setHorizontalTextPosition(AbstractButton.LEFT);
               second.setForeground(Color.blue);
               second.setFocusable(false);
               second.addActionListener(new ButtonAction2());
               third=new JButton("Simulation_3",opnerIcon);
               third.setHorizontalTextPosition(AbstractButton.LEFT);
               third.setForeground(Color.green);
               third.setFocusable(false);
               third.addActionListener(new ButtonAction3());
               fourth=new JButton("Simulation_4",opnerIcon);
               fourth.setHorizontalTextPosition(AbstractButton.LEFT);
               fourth.setForeground(Color.orange);
               fourth.setFocusable(false);
               fourth.addActionListener(new ButtonAction4());
               fifth=new JButton("Simulation_5",opnerIcon);
               fifth.setHorizontalTextPosition(AbstractButton.LEFT);
               fifth.setForeground(Color.cyan);
               fifth.setFocusable(false);
               fifth.addActionListener(new ButtonAction5());
               // textfields
               firstT=new JTextField(14);
               firstT.setEditable(false);
               secondT=new JTextField(14);
               secondT.setEditable(false);
               thirdT=new JTextField(14);
               thirdT.setEditable(false);
               fourthT=new JTextField(14);
               fourthT.setEditable(false);
               fifthT=new JTextField(14);
               fifthT.setEditable(false);
               // viewer button
               viewer=new JButton("View Result");
               viewer.setFocusable(false);
               viewer.addActionListener(this);
               //quit button
               quit=new JButton("        Exit        ");
               quit.setFocusable(false);
               quit.addActionListener(new QuitButtonListener(this));
               //add them to panel
               base=new JPanel();
               // layout manager
            gridbag = new GridBagLayout();
              c = new GridBagConstraints();
            base.setLayout(gridbag);
            base.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            // set constarins for the panel
            //add combo box
            c.gridx = 0;
            c.gridy = 0;
            c.gridheight = 1;
            c.gridwidth = 2;
            c.insets = new Insets(10,0,50,45);
            c.anchor = GridBagConstraints.CENTER;
            gridbag.setConstraints(selector, c);
            base.add(selector);          
            // first set
            c.gridx = 0;
            c.gridy = 1;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(10,0,10,10);
            gridbag.setConstraints(first, c);
            base.add(first);
            c.gridx = 1;
            c.gridy = 1;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(10,0,10,10);
            gridbag.setConstraints(firstT, c);
            base.add(firstT);
            //second set
            c.gridx = 0;
            c.gridy = 2;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(10,0,10,10);
            gridbag.setConstraints(second, c);
            base.add(second);
            c.gridx = 1;
            c.gridy = 2;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(10,0,10,10);
            gridbag.setConstraints(secondT, c);
            base.add(secondT);
            // third set
            c.gridx = 0;
            c.gridy = 3;
            c.gridheight = 1;
            c.gridwidth = 1;
            gridbag.setConstraints(third, c);
            c.insets = new Insets(10,0,10,10);
            base.add(third);
            c.gridx = 1;
            c.gridy = 3;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(10,0,10,10);
            gridbag.setConstraints(thirdT, c);
            base.add(thirdT);
               //fourth set
               c.gridx = 0;
            c.gridy = 4;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(10,0,10,10);
            gridbag.setConstraints(fourth, c);
            base.add(fourth);
            c.gridx = 1;
            c.gridy = 4;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(10,0,10,10);
            gridbag.setConstraints(fourthT, c);
            base.add(fourthT);     
            //fifth set
            c.gridx = 0;
            c.gridy = 5;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(10,0,10,10);
            gridbag.setConstraints(fifth, c);
            base.add(fifth);
            c.gridx = 1;
            c.gridy = 5;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(10,0,10,10);
            gridbag.setConstraints(fifthT, c);
            base.add(fifthT);
            //the viewer button          
            c.gridx = 0;
            c.gridy = 6;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(15,0,0,0);
            c.anchor = GridBagConstraints.CENTER;
            gridbag.setConstraints(viewer, c);
            base.add(viewer);
            //the quit button          
            c.gridx = 1;
            c.gridy = 6;
            c.gridheight = 1;
            c.gridwidth = 1;
            c.insets = new Insets(15,0,0,0);
            c.anchor = GridBagConstraints.CENTER;
            gridbag.setConstraints(quit, c);
            base.add(quit);
            base.setPreferredSize(new Dimension(320,440));
            title=BorderFactory.createTitledBorder("Simulation Comparison");
              base.setBorder(title);
              base.setVisible(true);
            base.setOpaque(true);
            base.updateUI();
            //split pane creation
            hPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
            boolean b = hPane.isContinuousLayout();  // false by default
              hPane.setContinuousLayout(true);
              b = hPane.isOneTouchExpandable();        // false by default
                hPane.setOneTouchExpandable(true);
            //hPane.resetToPreferredSizes();
            hPane.setDividerLocation(365);
            //allocate left component
            hPane.setLeftComponent(base);
            //allocate right component with a default graph panel
            DefaultGraph prelude=new DefaultGraph();
            graphic=new JPanel();
            graphic.add(prelude);
            graphic.setPreferredSize(new Dimension(590,440));
            graphic.setVisible(true);
            graphic.validate();
            hPane.setRightComponent(graphic);
            hPane.setPreferredSize(new Dimension(945,440));
            hPane.setVisible(true);
            return hPane;
         // action performed for view Result button
                public void actionPerformed (ActionEvent e) {
                 if(modus.equals(FIMBOTH))
                        System.out.println("3");
                       for(int i=50,j=0;i<75;i++,j++)
                            supply1[j]=reader1;
                        supply2[j]=reader2[i];
                        supply3[j]=reader3[i];
                        supply4[j]=reader4[i];
                        supply5[j]=reader5[i];
         else if(modus.equals(FIME))
              System.out.println("2");
              for(int i=25,j=0;i<50;i++,j++)
                   supply1[j]=reader1[i];
                   supply2[j]=reader2[i];
                   supply3[j]=reader3[i];
                   supply4[j]=reader4[i];
                   supply5[j]=reader5[i];
         else if (modus.equals(FIMB))
              System.out.println("1");
              for(int i=0;i<25;i++)
                   supply1[i]=reader1[i];
                   supply2[i]=reader2[i];
                   supply3[i]=reader3[i];
                   supply4[i]=reader4[i];
                   supply5[i]=reader5[i];
              System.out.println("works fine!");
              if(isChange)
                   viewer.setEnabled(false);
              else
                   System.out.println("button enabled");     
         // add GraphReceptorData panel to the splitPane
         GraphReceptorData graph = new GraphReceptorData(this);
         graphic.removeAll();
         graphic.add(graph);
    //reset the divider location
    hPane.setDividerLocation(365);
    //repaint the pane after change
    graphic.validate();
    graphic.paintImmediately(graph.getX(),graph.getY(),570,400);
    //add graph to the the split pane finally
    hPane.setRightComponent(graphic);
    // isChange boolean method
    public boolean isChanged() {
         if ((first.isSelected())||(second.isSelected())
         ||(third.isSelected())||(fourth.isSelected())||
         (fifth.isSelected()))
              isChange=true;
         return isChange;
    //Action listeners for buttons
    class ButtonAction1 implements ActionListener {
         public void actionPerformed (ActionEvent e) {
         //Handle open button action.
    if (e.getSource() == first) {
    int returnVal = fc.showDialog(GraphPane.this,"Attach");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
         try
         File file = fc.getSelectedFile();
    //loading the file onto the application interface
    firstT.setText(fc.getName(file));
    RandomAccessFile simulation1=new RandomAccessFile(firstT.getText(),"r");
    if ((firstT.getText().equals(fourthT.getText()))||(firstT.getText().equals(thirdT.getText()))||(firstT.getText().equals(secondT.getText()))||(firstT.getText().equals(fifthT.getText())))
              firstT.setText("");
              JOptionPane.showMessageDialog(null,"File selected has been already choosen","Selection Error",JOptionPane.ERROR_MESSAGE);
         else {
              for(int i=0;i<300;i+=4)
                   simulation1.seek(i);
              reader1[i/4]=simulation1.readInt();
    }          // end try
    catch (Exception locationError)
         System.out.println("Not executed");
    } else {
    System.out.println("Invalid selection");
         class ButtonAction2 implements ActionListener {
    // action performed for button2
    public void actionPerformed (ActionEvent e) {
    //Handle open button action.
    if (e.getSource() == second) {
    int returnVal = fc.showDialog(GraphPane.this,"Attach");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
         try
         File file = fc.getSelectedFile();
    //loading the file onto the application interface
    secondT.setText(fc.getName(file));
    RandomAccessFile simulation2=new RandomAccessFile(secondT.getText(),"r");
         if ((secondT.getText().equals(firstT.getText()))||(secondT.getText().equals(thirdT.getText()))||(secondT.getText().equals(fourthT.getText()))||(secondT.getText().equals(fifthT.getText())))
              secondT.setText("");
              JOptionPane.showMessageDialog(null,"File selected has been already choosen","Selection Error",JOptionPane.ERROR_MESSAGE);
    else {
         for(int i=0;i<300;i+=4)
                   simulation2.seek(i);
              reader2[i/4]=simulation2.readInt();
    }          // end try
    catch (Exception locationError)
         System.out.println("Not executed");
    } else {
    System.out.println("Invalid selection");
    class ButtonAction3 implements ActionListener {
    //action performed for button3
    public void actionPerformed (ActionEvent e) {
    //Handle open button action.
    if (e.getSource() == third) {
    int returnVal = fc.showDialog(GraphPane.this,"Attach");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
         try
         File file = fc.getSelectedFile();
    //loading the file onto the application interface
    thirdT.setText(fc.getName(file));
    RandomAccessFile simulation3=new RandomAccessFile(thirdT.getText(),"r");
    if ((thirdT.getText().equals(firstT.getText()))||(thirdT.getText().equals(secondT.getText()))||(thirdT.getText().equals(fourthT.getText()))||(thirdT.getText().equals(fifthT.getText())))
              thirdT.setText("");
              JOptionPane.showMessageDialog(null,"File selected has been already choosen","Selection Error",JOptionPane.ERROR_MESSAGE);
         else {
              for(int i=0;i<300;i+=4)
                        simulation3.seek(i);
                   reader3[i/4]=simulation3.readInt();
    }                    // end try
    catch (Exception locationError)
         System.out.println("Not executed");
    } else {
    System.out.println("Invalid selection");
    class ButtonAction4 implements ActionListener {  
    //action performed for button4
    public void actionPerformed (ActionEvent e) {
    //Handle open button action.
    if (e.getSource() == fourth) {
    int returnVal = fc.showDialog(GraphPane.this,"Attach");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
         try
         File file = fc.getSelectedFile();
    //loading the file onto the application interface
    fourthT.setText(fc.getName(file));
    RandomAccessFile simulation4=new RandomAccessFile(fourthT.getText(),"r");
    if ((fourthT.getText().equals(thirdT.getText()))||(fourthT.getText().equals(secondT.getText()))||(fourthT.getText().equals(firstT.getText()))||(fourthT.getText().equals(fifthT.getText())))
              fourthT.setText("");
              JOptionPane.showMessageDialog(null,"File selected has been already choosen","Selection Error",JOptionPane.ERROR_MESSAGE);
              else {
                   for(int i=0;i<300;i+=4)
                        simulation4.seek(i);
                   reader4[i/4]=simulation4.readInt();
    }               //end try
    catch (Exception locationError)
         System.out.println("Not executed");
    } else {
    System.out.println("Invalid selection");
    class ButtonAction5 implements ActionListener {   
    //action performed for button5
    public void actionPerformed (ActionEvent e) {
    //Handle open button action.
    if (e.getSource() == fifth) {
    int returnVal = fc.showDialog(GraphPane.this,"Attach");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
         try
         File file = fc.getSelectedFile();
    //loading the file onto the application interface
    fifthT.setText(fc.getName(file));
    RandomAccessFile simulation5=new RandomAccessFile(fifthT.getText(),"r");
    if ((fifthT.getText().equals(fourthT.getText()))||(fifthT.getText().equals(thirdT.getText()))||(fifthT.getText().equals(secondT.getText()))||(fifthT.getText().equals(firstT.getText())))
              fifthT.setText("");
              JOptionPane.showMessageDialog(null,"File selected has been already choosen","Selection Error",JOptionPane.ERROR_MESSAGE);
         else {
              for(int i=0;i<300;i+=4)
                        simulation5.seek(i);
                   reader5[i/4]=simulation5.readInt();
    }               //end try
    catch (Exception locationError)
         System.out.println("Not executed");
    } else {
    System.out.println("Invalid selection");
    //selector listener     
         class ModeListener implements ItemListener {
    // This method is called only if a new item has been selected.
    public void itemStateChanged(ItemEvent evt) {
    selector = (JComboBox)evt.getSource();
    // Get the affected item
    String s=(String)selector.getSelectedItem();
    if (evt.getStateChange() == ItemEvent.SELECTED) {
    // Item selected
    modus=s;
    System.out.println("cell selected is " + modus);
                             } else if (evt.getStateChange() == ItemEvent.DESELECTED) {
    // Item is no longer selected
              }     // end of mode listener
         // Returns an ImageIcon, or null if the path was invalid
    protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = GraphPane.class.getResource(path);
    if (imgURL != null) {
    return new ImageIcon(imgURL);
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    //get methods to retrieve the values of supply arrays to feed into GraphReceptorData class
    public int[] getSupplyOne() {
         return supply1;
    public int[] getSupplyTwo() {
         return supply2;
    public int[] getSupplyThree() {
         return supply3;
    public int[] getSupplyFour() {
         return supply4;
    public int[] getSupplyFive() {
         return supply5;
    // listener for the exit button                
         class QuitButtonListener implements ActionListener {
              private Window myWindow;
              public QuitButtonListener(Window w) {
                   myWindow = w; }
                   public void actionPerformed(ActionEvent evt) {
                   myWindow.setVisible(false);
                   myWindow.dispose();
    ######################## parent class#################
    the button there is just calling this class.
    // ActionListener for viewGraph button
    class ButtonGraph implements ActionListener {
         public void actionPerformed(ActionEvent e) {
             JFrame frame=new JFrame("Graph view screen");
             frame.getContentPane().add(new GraphPane().createViewcom(), BorderLayout.CENTER);
             frame.setSize(945, 440);
             frame.setResizable(false);
             frame.setVisible(true);
         }hope this will explain more...
    thanks a lot for help guys

  • JFileChooser DIRECTORIES ONLY mode

    When I use a JFileChooser with the mode as directories only, I want to show the full path of the directory selected by the user in the text box next to the File Name: label. However all that is being displayed is the name of the directory itself and not it's full directory path?
    JFileChooser jfc = new JFileChooser();
    jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    String strDirSel = jfc.getSelectedFile().getPath();
    jfc.setSelectedFile(new File(strDirSel));
    Any suggestions of how to manage this, would be appreciated?

    I thought the AWT one is a FILES_ONLY type of browser as well.
    I just figured a kludge that I'm willing to live with. I added a PropertyChangedListener to tell when a file was selected. This has the effect of drilling down on single-click. I first tried the code that is commented out. Although my debugging comments show up on the console, the directory was not changed for DIRECTORY_CHANGED_PROPERTY. Oh well.
    jFileChooser.addPropertyChangeListener(new PropertyChangeListener()
    public void propertyChange(PropertyChangeEvent evt)
    if (evt.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY))
    System.out.println("sfcp");
    File file = (File) evt.getNewValue();
    if (isShowing())
    if ( file.isDirectory())
    jFileChooser.setCurrentDirectory(file);
    if (evt.getPropertyName().equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY))
    System.out.println("DC");
    File file = (File) evt.getNewValue();
    if (isShowing())
    System.out.println("is showing");
    if (file.isDirectory())
    System.out.println("is directory");
    jFileChooser.setCurrentDirectory(file);

  • Is it possible to use fullscreen and exclusive mode with a jfilechooser?

    is there a way to use them together? while in fullscreen exclusive mode the jfilechooser doesn't attach to fullscreen window and it halts the program.. I've tried setting the parent frame as the fullscreen frame but it's all glitched.. am I missing something?
    thank you,
    best regards,
    Jacopo

    For reference, the cross-post can be found here:
    Is it possible to use network devices (cDAQ-9188) with a PXI Real Time system?
    Jayme W.
    Applications Engineer
    National Instruments

  • Default JFileChooser to details mode

    Hi all,
    In JFileChooser there are 2 JToggleButtons : "details" and "List.".
    each one switch the file chooser to corresponding view.the default is List view mode.
    I want my filechooser to always default to details view mode . is there a clean and easy way to achieve this ?
    thanks.

    In future Swing related question should be posted into the Swing forum.
    I am pretty sure (99%) the answer to your question is no.

  • How to set the the file selection mode of JFileChooser

    hi,
    i want to set the file selection mode to directories only for JFileChooser class but when i run the code it does not select the folder adn opens the folder instead. i want the user to select a folder from the file system . any ideas?

    Sorry, I misunderstood you question. I thought that you already set it to choose Directories and wondered when you can't select them when you double-click.
    use JFileChooser.setFileSelectionMode(int). This should solve your problem.
    Here is an example:
            JFileChooser jf = new JFileChooser();
            jf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            jf.showDialog(this, "Select");
            System.out.println(jf.getSelectedFile());
    unformatted
    JFileChooser jf = new JFileChooser();
    jf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    jf.showDialog(this, "Select");
    System.out.println(jf.getSelectedFile());

  • Quick question: JFileChooser mode

    Hello All,
    I have a bit of a problem regarding JFileChooser. My application has 1 main window, and subwindows which are created when certain actions are performed on the main window. I want to create a file chooser when I perform certain actions on one of the subwindows, and make that chooser modal with respect to the subwindow only. I want to be able to perform other operations on the main window, even if the file chooser is shown. Is this possible?
    Currently, I have a JFileChooser sublclass, and I tried to override the createDialog() method so that I can manipulate the shown dialog's modal property. So far this approach of changing the modal property does not get me close to the behavior I want. [ The dialog does not block when modal is set to false, and setting it to true makes the other windows inoperable. ]
    Does anyone have any idea regarding this problem? Please let me know.
    Thanks.
    Regards,
    Cocoh

    I am pretty sure that the modality (is that a word?) of a Dialog is by definition application wide. To do what you want you will probably have to manually enforce the single window modality. You could probably do this by adding a WindowFocusListener to your disabled window that will force focus to your quasi-modal window.
    Hope this helps,
    Josh Castagno
    http://www.jdc-software.com

  • JFileChooser : Exception occurred during event dispatching

    Hi,
    I'm having problems with sorting in 'Details' view of JFileChooser. I'm getting the following NullPointerException when I try to sort by clicking on the header of the JTable which I get in 'Details' view of a JFileChooser.
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at java.awt.EventQueue.isDispatchThread(Unknown Source)
    at javax.swing.SwingUtilities.isEventDispatchThread(Unknown Source)
    at javax.swing.JComponent.revalidate(Unknown Source)
    at javax.swing.JTable.resizeAndRepaint(Unknown Source)
    at javax.swing.JTable.sortedTableChanged(Unknown Source)
    at javax.swing.JTable.sorterChanged(Unknown Source)
    at javax.swing.RowSorter.fireRowSorterChanged(Unknown Source)
    at javax.swing.RowSorter.fireRowSorterChanged(Unknown Source)
    at javax.swing.DefaultRowSorter.sort(Unknown Source)
    at sun.swing.FilePane$DetailsTableRowSorter.access$1301(Unknown Source)
    at sun.swing.FilePane$DetailsTableRowSorter$1.call(Unknown Source)
    at sun.swing.FilePane$DetailsTableRowSorter$1.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Any operation performed in the JFileChooser after this exception will generate the same exception & no action is performed. I'm using Java 1.6.0_24. Strangely, this is happening only in client-server mode. Staand-alone is working fine.
    Please provide some urgent inputs to this problem
    Thanks
    Dilip

    Thanks 4 d reply mKorbel, I'm not creating a TableModel. I'm just creating a JFileChooser as shown below.
    JFileChooser fileChooser = new JFileChooser(location);
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setDialogTitle("Choose File");
    if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
    Now, the scenario is to bringup the FileChooser, go to Details view, apply sort on any column. This action creates the mentioned NullPointerException.

  • JFileChooser and FilePermission write

    Hi,
    I use a JFileChooser in a swing application like this :
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    if (fileChooser.showOpenDialog(MainJWS.this)== JFileChooser.APPROVE_OPTION) {
    dir2Name = fileChooser.getSelectedFile().getPath();
    I want the application to only get rights on FilePermission to read. So I change my policy file like this :
    grant {
    permission java.io.FilePermission "<<ALL FILES>>", "read";
    So when the appli runs, there is a PermissionException on write right. Is there any way to use the JFileChooser only on a read mode ?
    thanks.

    Thanks, I saw it.
    Maybe there 's another way, with FileDialog ? Or with JFileChooser and FileSystemView ?
    any idea ?

  • JFileChooser's approve button text changes when file

    I have a JFileChooser used for loading some XML file(s). We want the approve button's text to be "Load". When I bring up the dialog, the button text initially reads "Load", when I select a directory, it reads "Open", if I select a file again, it goes back to "Load". So far, so good.
    The problem comes when using it in a non-English language. When I bring up the dialog, the button text initially reads the appropriately translated "Load". However, when I select a directory, it changes to the English "Open". I do not see a method to use to adjust this text. Am I missing something, or is this a bug?
    Any help is greatly appreciated.
    Jamie

    Here's some code I'll put into the public domain:
    package com.graphbuilder.desktop;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Stack;
    import java.util.Vector;
    import java.util.StringTokenizer;
    import java.io.File;
    <p>Attempt to improve the behaviour of the JFileChooser.  Anyone who has used the
    the JFileChooser will probably remember that it lacks several useful features.
    The following features have been added:
    <ul>
    <li>Double click to choose a file</li>
    <li>Enter key to choose a file after typing the filename</li>
    <li>Enter key to change to a different directory after typing the filename</li>
    <li>Automatic rescanning of directories</li>
    <li>A getSelectedFiles method that returns the correct selected files</li>
    <li>Escape key cancels the dialog</li>
    <li>Access to common GUI components, such as the OK and Cancel buttons</li>
    <li>Removal of the useless Update and Help buttons in Motif L&F</li>
    </ul>
    <p>There are a lot more features that could be added to make the JFileChooser more
    user friendly.  For example, a drop-down combo-box as the user is typing the name of
    the file, a list of currently visited directories, user specified file filtering, etc.
    <p>The look and feels supported are Metal, Window and Motif.  Each look and feel
    puts the OK and Cancel buttons in different locations and unfortunately the JFileChooser
    doesn't provide direct access to them.  Thus, for each look-and-feel the buttons must
    be found.
    <p>The following are known issues:  Rescanning doesn't work when in Motif L&F.  Some
    L&Fs have components that don't become available until the user clicks a button.  For
    example, the Metal L&F has a JTable but only when viewing in details mode.  The double
    click to choose a file does not work in details mode.  There are probably more unknown
    issues, but the changes made so far should make the JFileChooser easier to use.
    public class FileChooserFixer implements ActionListener, KeyListener, MouseListener, Runnable {
         Had to make new buttons because when the original buttons are clicked
         they revert back to the original label text.  I.e. some programmer decided
         it would be a good idea to set the button text during an actionPerformed
         method.
         private JFileChooser fileChooser = null;
         private JButton okButton = new JButton("OK");
         private JButton cancelButton = new JButton("Cancel");
         private JList fileList = null;
         private JTextField filenameTextField = null;
         private ActionListener actionListener = null;
         private long rescanTime = 20000;
         public FileChooserFixer(JFileChooser fc, ActionListener a) {
              fileChooser = fc;
              actionListener = a;
              fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              okButton.setMnemonic('O');
              cancelButton.setMnemonic('C');
              JButton oldOKButton = null;
              JButton oldCancelButton = null;
              JTextField[] textField = getTextFields(fc);
              JButton[] button = getButtons(fc);
              JList[] list = getLists(fc);
              String laf = javax.swing.UIManager.getLookAndFeel().getClass().getName();
              if (laf.equals("javax.swing.plaf.metal.MetalLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[1];
                   filenameTextField = textField[0];
                   fileList = list[0];
              else if (laf.equals("com.sun.java.swing.plaf.windows.WindowsLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[1];
                   filenameTextField = textField[0];
                   fileList = list[0];
              else if (laf.equals("com.sun.java.swing.plaf.motif.MotifLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[2];
                   button[1].setVisible(false); // hides the do-nothing 'Update' button
                   button[3].setVisible(false); // hides the disabled 'Help' button
                   filenameTextField = textField[1];
                   fileList = list[0];
              fix(oldOKButton, okButton);
              fix(oldCancelButton, cancelButton);
              okButton.addActionListener(this);
              cancelButton.addActionListener(this);
              fileList.addMouseListener(this);
              addKeyListeners(fileChooser);
              new Thread(this).start(); // note: rescanning in Motif feel doesn't work
         public void run() {
              try {
                   while (true) {
                        Thread.sleep(rescanTime);
                        Window w = SwingUtilities.windowForComponent(fileChooser);
                        if (w != null && w.isVisible())
                             fileChooser.rescanCurrentDirectory();
              } catch (Throwable err) {}
         public long getRescanTime() {
              return rescanTime;
         public void setRescanTime(long t) {
              if (t < 200)
                   throw new IllegalArgumentException("Rescan time >= 200 required.");
              rescanTime = t;
         private void addKeyListeners(Container c) {
              for (int i = 0; i < c.getComponentCount(); i++) {
                   Component d = c.getComponent(i);
                   if (d instanceof Container)
                        addKeyListeners((Container) d);
                   d.addKeyListener(this);
         private static void fix(JButton oldButton, JButton newButton) {
              int index = getIndex(oldButton);
              Container c = oldButton.getParent();
              c.remove(index);
              c.add(newButton, index);
              newButton.setPreferredSize(oldButton.getPreferredSize());
              newButton.setMinimumSize(oldButton.getMinimumSize());
              newButton.setMaximumSize(oldButton.getMaximumSize());
         private static int getIndex(Component c) {
              Container p = c.getParent();
              for (int i = 0; i < p.getComponentCount(); i++) {
                   if (p.getComponent(i) == c)
                        return i;
              return -1;
         public JButton getOKButton() {
              return okButton;
         public JButton getCancelButton() {
              return cancelButton;
         public JList getFileList() {
              return fileList;
         public JTextField getFilenameTextField() {
              return     filenameTextField;
         public JFileChooser getFileChooser() {
              return fileChooser;
         protected JButton[] getButtons(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JButton)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JButton[] arr = new JButton[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JButton) v.get(i);
              return arr;
         protected JTextField[] getTextFields(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JTextField)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JTextField[] arr = new JTextField[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JTextField) v.get(i);
              return arr;
         protected JList[] getLists(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JList)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JList[] arr = new JList[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JList) v.get(i);
              return arr;
         public File[] getSelectedFiles() {
              File[] f = fileChooser.getSelectedFiles();
              if (f.length == 0) {
                   File file = fileChooser.getSelectedFile();
                   if (file != null)
                        f = new File[] { file };
              return f;
         public void mousePressed(MouseEvent evt) {
              Object src = evt.getSource();
              if (src == fileList) {
                   if (evt.getModifiers() != InputEvent.BUTTON1_MASK) return;
                   int index = fileList.locationToIndex(evt.getPoint());
                   if (index < 0) return;
                   fileList.setSelectedIndex(index);
                   File[] arr = getSelectedFiles();
                   if (evt.getClickCount() == 2 && arr.length == 1 && arr[0].isFile())
                        actionPerformed(new ActionEvent(okButton, 0, okButton.getActionCommand()));
         public void mouseReleased(MouseEvent evt) {}
         public void mouseClicked(MouseEvent evt) {}
         public void mouseEntered(MouseEvent evt) {}
         public void mouseExited(MouseEvent evt) {}
         public void keyPressed(KeyEvent evt) {
              Object src = evt.getSource();
              int code = evt.getKeyCode();
              if (code == KeyEvent.VK_ESCAPE)
                   actionPerformed(new ActionEvent(cancelButton, 0, cancelButton.getActionCommand()));
              if (src == filenameTextField) {
                   if (code != KeyEvent.VK_ENTER) return;
                   fileList.getSelectionModel().clearSelection();
                   actionPerformed(new ActionEvent(okButton, 0, "enter"));
         public void keyReleased(KeyEvent evt) {}
         public void keyTyped(KeyEvent evt) {}
         public void actionPerformed(ActionEvent evt) {
              Object src = evt.getSource();
              if (src == cancelButton) {
                   if (actionListener != null)
                        actionListener.actionPerformed(evt);
              else if (src == okButton) {
                   File[] selectedFiles = getSelectedFiles();
                   Object obj = fileList.getSelectedValue(); // is null when no file is selected in the JList
                   String text = filenameTextField.getText().trim();
                   if (text.length() > 0 && (obj == null || selectedFiles.length == 0)) {
                        File d = fileChooser.getCurrentDirectory();
                        Vector vec = new Vector();
                        StringTokenizer st = new StringTokenizer(text, "\"");
                        while (st.hasMoreTokens()) {
                             String s = st.nextToken().trim();
                             if (s.length() == 0) continue;
                             File a = new File(s);
                             if (a.isAbsolute())
                                  vec.add(a);
                             else
                                  vec.add(new File(d, s));
                        File[] arr = new File[vec.size()];
                        for (int i = 0; i < arr.length; i++)
                             arr[i] = (File) vec.get(i);
                        selectedFiles = arr;
                   if (selectedFiles.length == 0) {
                        Toolkit.getDefaultToolkit().beep();
                        return;
                   if (selectedFiles.length == 1) {
                        File f = selectedFiles[0];
                        if (f.exists() && f.isDirectory() && text.length() > 0 && evt.getActionCommand().equals("enter")) {
                             fileChooser.setCurrentDirectory(f);
                             filenameTextField.setText("");
                             filenameTextField.requestFocus();
                             return;
                   boolean filesOnly = (fileChooser.getFileSelectionMode() == JFileChooser.FILES_ONLY);
                   boolean dirsOnly = (fileChooser.getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY);
                   if (filesOnly || dirsOnly) {
                        for (int i = 0; i < selectedFiles.length; i++) {
                             File f = selectedFiles;
                             if (filesOnly && f.isDirectory() || dirsOnly && f.isFile()) {
                                  Toolkit.getDefaultToolkit().beep();
                                  return;
                   fileChooser.setSelectedFiles(selectedFiles);
                   if (actionListener != null)
                        actionListener.actionPerformed(evt);

  • JFileChooser - show files and directories only select directory

    I need a JFileChooser that will display directories and zip files but only allow a directory to be selected.
    basically i need to be able to select a certain directory that contains a certain zip file, so to make it easier to find i want the zip files to show up so i can find the correct directory...
    I tried...
            JFileChooser jfc = new JFileChooser();
            jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            jfc.setFileFilter(new FileFilter() {
                public boolean accept(File f) {
                    if (f.isDirectory()) {
                        return true;
                    else if (f.getName().endsWith(".zip")) {
                        return true;
                    return false;
                public String getDescription() {
                    return "testing";
            });but that only displays directories in the GUI.
    The javadoc for the setFileSelectionMode() says, "Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories. The default is JFilesChooser.FILES_ONLY. " ....which makes you think that setting the file selection mode only alters what can be SELECTED...however it alters what is displayed as well.
    ...any ideas?
    thanks

    This should display the files of interest provided the filter is tuned to do so, and allow you to select either the file of interest or the folder... If you select the file, then folder it is contained is returned.
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    MyFileFilter filter = new MyFileFilter();
    chooser.setFileFilter(filter);
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {              
      System.out.println(chooser.getCurrentDirectory());
    }

  • JFileChooser view are listed as details

    How can I change the way files are shown in my JFileChooser?
    I want to show them like Windows XP shows the details mode.
    Besides, I still want to order them in Descending names order.
    So far I have this:
    The viewer:
    class PreviewPanel extends JPanel {
            public PreviewPanel() {
                JLabel label = new JLabel("EDI Viewer", SwingConstants.CENTER);
                setPreferredSize(new Dimension(350,0));
                setBorder(BorderFactory.createEtchedBorder());
                setLayout(new BorderLayout());
                label.setBorder(BorderFactory.createEtchedBorder());
                add(label, BorderLayout.NORTH);
                add(previewer, BorderLayout.CENTER);
        }The JFileChooser Box:
    private PreviewPanel  previewPanel = new PreviewPanel();
    chooser = new JFileChooser(new File(entryDir));
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setAccessory(previewPanel);
            chooser.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent e) {
                    if(e.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
                        previewer.configure((File)e.getNewValue());
            });Anyone's got something to say about this?
    Thanks

    I have chaged something but still not working, now I am using FileSystemView:
        class EDIFileSystemView extends FileSystemView {
            public File[] getFiles(File dir, boolean useFileHiding) {
                File newDir = new File(entryDir);
                File[] files = newDir.listFiles();
                Comparator nameComparator = new Comparator(){
                    public int compare(Object o1, Object o2){
                        String name1=((File)o1).getName();
                        String name2=((File)o2).getName();
                        return name2.compareTo(name1);
                Arrays.sort(files, nameComparator);
               // Here the files are shown in the correct order           
               for(int i=0; i<files.length; i++){
                    System.out.println("File: "+files);
    return files;
    public File createNewFolder(File containingDir) throws IOException {
    return containingDir;
    Calling JFileChooser (here the files DOES NOT appear in the correct order):
    chooser = new JFileChooser(new EDIFileSystemView());
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setAccessory(previewPanel);
            chooser.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent e) {
                    if(e.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
                        previewer.configure((File)e.getNewValue());
    Why is this happening?

Maybe you are looking for