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

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!

  • 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.

  • 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

  • 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;
    }

  • 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(".");

  • Enhanced JFileChooser for file encoding selection

    In many I18N applications, files are stored in different encodings, including Unicode formats. It would be very useful for JFileChooser to have a file encoding selection mechanism similar to that in MS Windows' common file dialogs -- the "Encoding" box can be seen in Windows 2000/XP Notepad's File Open/Save dialog, directly under "File name" and "Save as type" combo boxes.
    This enhancement will make JFileChooser closely match Windows standard file dialogs and be a desirable option on other platforms as well.
    Vote for Bug Id 4935601:
    http://developer.java.sun.com/developer/bugParade/bugs/4935601.html
    (also posted in Internationalization Forum)

    That is a good point! I think all of documents encoded in Unicode need this feature to be saved correctly.

  • How do I rewrite current code for java 1.3

    I'm using the code below that is written for java 1.4. I have been told that the company can not push JRE 1.4 to the company, and that I need to write my code for java 1.3. I'm using org.w3c.dom for my create xml, etc.
    Is there a java 1.3 option to the 1.4? Any help would be very appreciated.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.List;
    import java.io.*;
    import java.util.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.*;
    public class Sametime extends JFrame implements ActionListener {
        private int indentation = -1;
        JPanel panel = new JPanel();
        JTextArea jta = new JTextArea(
        //Instructions for user
        "For a successful buddy list migration do the following:\n"
        + "1. Save your current Sametime Buddy List to your PC.\n   "
        + "The default location should be: C:/Program Files/Lotus/Sametime Client.\n"
        + "  A. Open the Sametime Client.\n"
        + "  B. Click on People\n"
        + "  C. Click on Save List.\n"
        + "  D. Save as your first.last.dat\n"
        + "     Ex. john.doe.dat\n"
        + "NOTE: If you have AOL contacts in your Sametime buddy list they will not be migrated.\n");
        JButton browse = new JButton("Continue");
        JButton exit = new JButton("Exit");
        public Sametime() {
            super("Sametime Buddy List Migration");
            setSize(610, 245);
            Container c = this.getContentPane();
            c.add(panel);
            browse.addActionListener(this);
            exit.addActionListener(this);
            panel.add(jta);
            panel.add(browse);
            panel.add(exit);
            jta.setEditable(false);
            setLookAndFeel();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        } //end Sametime
        public class DATFilter extends javax.swing.filechooser.FileFilter {
            public boolean accept(File f) {
                //if it is a directory -- we want to show it so return true.
                if (f.isDirectory())
                    return true;
                String extension = getExtension(f);//get the extension of the file
                //check to see if the extension is equal to "dat"
                if ((extension.equals("dat")))
                    return true;
                //default -- fall through. False is return on all
                //occasions except:
                //a) the file is a directory
                //b) the file's extension is what we are looking for.
                return false;
            }//end accept
            public String getDescription() {
                return "dat files";
            }//end getDescription
             * Method to get the extension of the file, in lowercase
            private String getExtension(File f) {
                String s = f.getName();
                int i = s.lastIndexOf('.');
                if (i > 0 &&  i < s.length() - 1)
                    return s.substring(i+1).toLowerCase();
                return "";
            }//end getExtension
        }//end class DATFilter
        public void actionPerformed(ActionEvent e) {
            //Default Location for JFileChooser search
            String error = "The file selected is not a .dat file!\n"
            + "Please select your recently saved .dat file and try again.";
            JFileChooser fc = new JFileChooser("/Program Files/Lotus/Sametime Client");
            fc.setFileFilter(new DATFilter());
            fc.setFileSelectionMode( JFileChooser.FILES_ONLY);
            String user = System.getProperty("user.name");// finds who the current user is
            if (e.getSource() == browse) {
                int returnVal = fc.showSaveDialog(Sametime.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    //if (fc.getSelectedFile().getName().equals(".dat")){
                    if (fc.getSelectedFile().getName().endsWith(".dat")){ // checks to see if selected file is .dat
                    }else{
                        JOptionPane.showMessageDialog(null, error, "Wrong File", JOptionPane.ERROR_MESSAGE);
                        return;
                    }//end else
                    try {
                        String[] contactArray = parseDatFile(fc.getSelectedFile());
                        Document document = createXMLDocument(contactArray);
                        saveToXMLFile(
                        document,
                        new File(
                        "C:/Documents and Settings/" + user +"/My Documents/OLCS/",// looks for directory for list
                        "contacts-list_migration.ctt"));
                    } catch (Exception exc) {
                        File f = new File("C:/Documents and Settings/" + user +"/My Documents/OLCS/");// setting directory for list if not there
                        boolean yes = true;
                        yes = f.mkdir();// creating directory
                        try {
                            String[] contactArray = parseDatFile(fc.getSelectedFile());
                            Document document = createXMLDocument(contactArray);
                            saveToXMLFile(
                            document,
                            new File(
                            "C:/Documents and Settings/" + user +"/My Documents/OLCS/",// used only if the directory didn't exist
                            "contacts-list_migration.ctt"));
                            //exc.printStackTrace();// not sure if this is needed?
                        } catch (Exception exc1) {
                            exc1.printStackTrace();
                        }//end inner catch
                    }// end catch
                }// end if
                if(returnVal==JFileChooser.CANCEL_OPTION){
                    String Warning = "You did not migrate your Sametime buddy list at this time.";
                    JOptionPane.showMessageDialog(null, Warning, "Migration Canceled", JOptionPane.WARNING_MESSAGE);
                    return;
                }else{
                    String thankyou = "Thank You for Migrating your Sametime buddy list to OLCS"
                    + "\nYour new OLCS buddy list has been saved to:"
                    + "\nC:/Documents and Settings/" + user +"/My Documents/OLCS"
                    + "\n as: Contact-List_migration.ctt"
                    + "\n\n To be able to use Contact-List_migration.ctt for Windows Messenger:"
                    + "\n1. Log into Windows Messenger."
                    + "\n2. Click on File"
                    + "\n3. Click on 'Import Contacts from a Saved File...'"
                    + "\n4. Open OLCS in My Documents"
                    + "\n5. Click on 'Contact-list_migration.ctt'"
                    + "\n6. Click Open to import the list."
                    + "\n   A window will pop up confirming that you want to add all of the contacts"
                    + "\n   Click 'yes'"
                    + "\n   Your buddy list is ready to be used.";
                    JOptionPane.showMessageDialog(null, thankyou, "Migration Completed", JOptionPane.INFORMATION_MESSAGE);//Change this when defualt directory is known.
                }//end if else statement
            } //end if
            System.exit( 0 );
            if (e.getSource() == exit) {
                System.exit( 0 );
            } //end if
        } //end actionPerformed
        String[] parseDatFile(File datFile)
        throws Exception    {
            List list = new ArrayList();
            BufferedReader br = new BufferedReader(new FileReader(datFile));
            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.indexOf("U") != 0)
                    continue;
                int p = line.indexOf("::");
                if (p == -1)
                    continue;
                line = line.substring(p + 2).trim();
                if (line.indexOf("AOL") == 0)
                    continue;
                p = line.indexOf(",");
                if (p != -1)
                    line = line.substring(0, p);
                line = line.trim() + "@mci.com";
                if (list.indexOf(line) == -1)
                    list.add(line);
            }//end while
            br.close();
            String[] contactArray = new String[list.size()];
            list.toArray(contactArray);
            return contactArray;
        }// end String
        // setting up the XML file
        Document createXMLDocument(String[] contactArray) throws Exception {
            DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dBF.newDocumentBuilder();
            DOMImplementation domImpl = builder.getDOMImplementation();
            Document document = domImpl.createDocument(null, "messenger", null);
            Element root = document.getDocumentElement();
            Element svcElm = document.createElement("service");
            Element clElm = document.createElement("contactlist");
            svcElm.setAttribute("name", "Microsoft RTC Instant Messaging");
            svcElm.appendChild(clElm);
            root.appendChild(svcElm);
            for (int i = 0; i < contactArray.length; i++) {
                Element conElm = document.createElement("contact");
                Text conTxt = document.createTextNode(contactArray);
    conElm.appendChild(conTxt);
    clElm.appendChild(conElm);
    }//end for
    return document;
    }// end Document
    void saveToXMLFile(Document document, File xmlFile) throws Exception {
    OutputStream os =
    new BufferedOutputStream(new FileOutputStream(xmlFile));
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");//puts information on seperate lines
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");//gives the XML file indentation
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    DOMSource source = new DOMSource(document);
    StreamResult result = new StreamResult(os);
    transformer.transform(source, result);
    os.close();
    }//end saveToXMLFile
    public static void main(String[] args) {
    Sametime st = new Sametime();
    ImageIcon picIcon = new ImageIcon(st.getClass().getResource("/images/mci.gif"));//Change when default is known!
    st.setIconImage(picIcon.getImage());
    } //end main
    private void setLookAndFeel() {
    try {
    UIManager.setLookAndFeel(
    UIManager.getSystemLookAndFeelClassName());
    SwingUtilities.updateComponentTreeUI(this);
    } catch (Exception e) {
    System.err.println("Could not use Look and Feel: " + e);
    } //end catch
    } //end void setLookAndFeel
    } //end public class Sametime

    Are there features of Java 1.4 that you specifically took advantage and are there any particular lines you are having problems with or did you just freak and post it here?
    Basically compile it under Java 1.3 and see what complains. I've done several projects that compile under 1.2, 1.3, and 1.4.

  • JFileChooser, multiple dialogs.

    My JFileChooser is getting the path and filename for a file, to be later opened. I'm placing the path and name in a JTextField.
    My problem is this: whenever I click 'Find' and select my file and click 'Open', the path and filename show in the JTextField, but the dialog reopens as though I'm pressing the 'Find' button again.
    Here's my source:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.filechooser.*;
    public class mm5 extends JFrame implements ActionListener
         String[] sItems = new String[1]; // Stores item titles loaded from file. Will be displayed in JList: lstItems
         String[] sProgram = new String[1]; // The program that is ran when the script is executed.
         String[] sLocation = new String[1]; // The location the program tries to open when the script is executed.
         int[] iTimer = new int[1]; // A value of zero will tell the program that this is a schedule-based item instead of a timer-based one.
         int[][] iTimeDef = new int[1][1]; // The first field in this matrix contains the number of scheduled times the item will be called. The second field contains the hour in which the item will be called.
         Border border1 = new EtchedBorder(EtchedBorder.RAISED, Color.black, new Color(165, 163, 151));
         JFrame fraAdminPanel = new JFrame("Admin Panel");
         JFrame fraAddItem = new JFrame("Add Item");
         JPanel panBack = new JPanel();
              JList lstItems = new JList();
              JScrollPane scpItems = new JScrollPane(lstItems);
              JButton btnRun = new JButton("Run");
              JButton btnReport = new JButton("Report");
              JButton btnInfo = new JButton("Info");
              JButton btnHelp = new JButton("Help");
              JButton btnAdmin = new JButton("Admin");
              JButton btnExit = new JButton("Exit");
              JLabel lblTime1 = new JLabel("Time");
              JLabel lblTime2 = new JLabel("00:00");
         JPanel panAdmin = new JPanel();
              JButton btnAddNew = new JButton("Add New");
         JPanel panAddItem = new JPanel();
              JLabel lblItem = new JLabel("Item Title/Desc.");
              JTextField txfItem = new JTextField(100);
              JLabel lblProgram = new JLabel("Program");
              JComboBox cbxProgram = new JComboBox();
              JLabel lblLocation = new JLabel("Location/URL");
              JTextField txfLocation = new JTextField(100);
              JFileChooser fcLocation = new JFileChooser();
              JButton btnLocation = new JButton("Find");
              ButtonGroup btgTimer = new ButtonGroup();
                   JRadioButton optTimer = new JRadioButton("Timer");
                   JRadioButton optTimeDef = new JRadioButton("Scheduled");
                   JRadioButton optNull = new JRadioButton("");
              JLabel lblTimer = new JLabel("Minutes");
              JTextField txfTimer = new JTextField(3);
              JLabel lblTimeDef = new JLabel("Schedule");
              JTextField txfTimeDef = new JTextField(3);
              JButton btnTimeDef = new JButton("Set");
              JCheckBox cbxException = new JCheckBox();
              JButton btnAdd = new JButton("Add Item");
              JButton btnCancel = new JButton("Cancel");
         public mm5()
              try
                   mmInit();
              catch(Exception e)
                   e.printStackTrace();
         } // End of mm5()
         public void actionPerformed(ActionEvent AE)
              String sTheAction = AE.getActionCommand();
              if(sTheAction == "Admin")
                   System.out.println("Admin button pressed.");
                   adminPanel();
              else if(sTheAction == "Add New")
                   System.out.println("Add New button pressed.");
                   addNewInit();
              else if(sTheAction == "Find")
                   System.out.println("Find button pressed.");
                   findFile();
         } // End of actionPerformed()
         public static void main(String[] args)
              mm5 f = new mm5();
         } // End of main()
         public void mmInit()
              this.setTitle("MultiMonitor 5.0.1");
              this.getContentPane().setLayout(null);
              centerWindow(700, 500); // Centers the window and sets the x,y size.
              addWindowListener(
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             System.exit(0);
              panBack.setLayout(null);
              panBack.setBounds(new Rectangle(5,5,695,495));
              BackLstItemsInit();
              panBack.add(scpItems, null);
              BackBtnInit();
              panBack.add(btnRun, null);
              panBack.add(btnReport, null);
              panBack.add(btnInfo, null);
              panBack.add(btnHelp, null);
              panBack.add(btnAdmin, null);
              panBack.add(btnExit, null);
              this.getContentPane().add(panBack);
              this.setVisible(true);
         } // End of mmInit()
         public void BackLstItemsInit()
              boolean EOF = false;
              scpItems.setBounds(new Rectangle(5,5,575,450));
              scpItems.setBorder(border1);
              scpItems.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              lstItems.setListData(sItems);
         } // End of BackLstItemsInit()
         public void BackBtnInit()
              btnRun.setBounds(new Rectangle(585,5,100,25));
                   btnRun.setActionCommand("Run");
                   btnRun.addActionListener(this);
              btnReport.setBounds(new Rectangle(585,30,100,25));
                   btnReport.setActionCommand("Report");
                   btnReport.addActionListener(this);
              btnInfo.setBounds(new Rectangle(585,55,100,25));
                   btnInfo.setActionCommand("Info");
                   btnInfo.addActionListener(this);
              btnHelp.setBounds(new Rectangle(585,80,100,25));
                   btnHelp.setActionCommand("Help");
                   btnHelp.addActionListener(this);
              btnAdmin.setBounds(new Rectangle(585,105,100,25));
                   btnAdmin.setActionCommand("Admin");
                   btnAdmin.addActionListener(this);
              btnExit.setBounds(new Rectangle(585,130,100,25));
                   btnExit.setActionCommand("Exit");
                   btnAdmin.addActionListener(this);
         } // End of BackBtnInit()
         public void centerWindow(int windowWidth, int windowHeight)
              Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              this.setBounds((d.width - windowWidth)/2, (d.height - windowHeight)/2, windowWidth, windowHeight);
         } // End of centerWindow()
         public String[] enlargeArray(String[] currentArray)
              String[] newArray = new String[currentArray.length + 1];
              for(int i = 0; i<currentArray.length; i++)
                   newArray[i] = currentArray;
              return newArray;
         } // End of enlargeArray()
         public void adminPanel()
              System.out.println("adminPanel() started");
              fraAdminPanel.setVisible(true);
              fraAdminPanel.getContentPane().add(panAdmin);
              fraAdminPanel.setBounds(50,50,100,200);
              panAdmin.setLayout(null);
              panAdmin.setBounds(0,0,110,200);
              btnAddNew.setBounds(new Rectangle(5,5,100,25));
                   btnAddNew.setActionCommand("Add New");
                   btnAddNew.addActionListener(this);
                   panAdmin.add(btnAddNew, null);
         } // End of adminPanel()
         public void addNewInit()
              System.out.println("addItem() started");
              fraAddItem.setVisible(true);
              fraAddItem.getContentPane().add(panAddItem);
              fraAddItem.setBounds(50,50,325,250);
              panAddItem.setLayout(null);
                   panAddItem.setBounds(0,0,325,250);
              lblItem.setBounds(new Rectangle(5,5,200,25));
                   panAddItem.add(lblItem, null);
              txfItem.setBounds(new Rectangle(5,35,200,25));
                   panAddItem.add(txfItem, null);
              lblProgram.setBounds(new Rectangle(210,5,100,25));
                   panAddItem.add(lblProgram, null);
              cbxProgram.setBounds(new Rectangle(210,35,100,25));
                   panAddItem.add(cbxProgram, null);
              lblLocation.setBounds(new Rectangle(5,65,200,25));
                   panAddItem.add(lblLocation, null);
              txfLocation.setBounds(new Rectangle(5,95,200,25));
                   panAddItem.add(txfLocation, null);
              btnLocation.setBounds(new Rectangle(210,95,100,25));
                   btnLocation.setActionCommand("Find");          // Button for JFileChooser
                   btnLocation.addActionListener(this);
                   panAddItem.add(btnLocation, null);
              optTimer.setBounds(new Rectangle(5,125,100,25));
                   optTimer.setActionCommand("optTimer");
                   optTimer.addActionListener(this);
                   btgTimer.add(optTimer);
                   panAddItem.add(optTimer, null);
              optTimeDef.setBounds(new Rectangle(105,125,100,25));
                   optTimeDef.setActionCommand("optTimeDef");
                   optTimeDef.addActionListener(this);
                   btgTimer.add(optTimeDef);
                   panAddItem.add(optTimeDef, null);
              optNull.setActionCommand("optNull");
                   optNull.addActionListener(this);
                   btgTimer.add(optNull);
              lblTimer.setBounds(new Rectangle(5,155,100,25));
                   panAddItem.add(lblTimer, null);
              txfTimer.setBounds(new Rectangle(5,185,100,25));
                   panAddItem.add(txfTimer, null);
              lblTimeDef.setBounds(new Rectangle(105,155,100,25));
                   panAddItem.add(lblTimeDef, null);
              btnTimeDef.setBounds(new Rectangle(105,185,100,25));
                   panAddItem.add(btnTimeDef, null);
              btnAdd.setBounds(new Rectangle(210,155,100,25));
                   btnAdd.setActionCommand("Add");
                   btnAdd.addActionListener(this);
                   panAddItem.add(btnAdd, null);
              btnCancel.setBounds(new Rectangle(210,185,100,25));
                   btnCancel.setActionCommand("Cancel Add");
                   btnCancel.addActionListener(this);
                   panAddItem.add(btnAdd, null);
         } // End of addNewInit()
         public void findFile()
              fcLocation.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              int iLocation = fcLocation.showOpenDialog(fraAddItem);
              if(iLocation == JFileChooser.APPROVE_OPTION)
                   txfLocation.setText(fcLocation.getCurrentDirectory() + "\\" + fcLocation.getSelectedFile().getName());
                   System.out.println(fcLocation.getSelectedFile().getName() + " selected");
              else
                   System.out.println("No file selected.");
                   return;
         } // End of findFile()

    The problem is with he registration of actionListener for the find button.
    This is being done in your code each time the AddNewItem is being
    used. because of this each time you click Add New Item. another listener
    is registered for the find button and hence the no. of times it will
    show filechooser will keep on increasing.
    Pravin

  • How do you add a combo box into a Jfilechooser?

    how do you add a combo box into a Jfilechooser?
    thanks

    See the API For JFileChooser
    public void setAccessory(JComponent newAccessory)Extend a JPanel or Such like, put your Combo Box on it, fiddle around with event handling code for the ComboBox..
    Set an Instance of that as The Accessory for the JFileChooser.
    Look In Your Docs:-
    <JAVA_HOME>/Demo/jfc/SwingSet2/src , unpack SwingSet2.jar if neccessary
    In there is a demo of using A JFileChooser with an accessory Panel, and Source code that is adaptable...

  • JFileChooser Network Folder Issue

    Hello all
    Class : javax.swing.JFileChooser (network folders)
    J2SE : 1.4
    OS : Windows
    I'm in need of urgent help for JFileChooser, scenerio is, currently when I do a open or save dialog using the JFileChooser it brings up the mapped network folders along with local folders on my PC.
    For selection, if I clicked on the network folders, is there a way I could differentiate if it was one of the mapped network folders or a regular file on the file system? I dont see any of the folders underneath my network folder, it just doesnt seem to work right.
    Also the mapped network folder is username password protected which comes up with the Username Password prompt dialog the first time I access it through the open / save dialogs, where exactly does it store this information.
    Any help would be highly appreciated.
    Regards

    I'm assuming that we are still talking about mapped network drives
    under "My Computer", as opposed to navigating "Network Neighborhood"
    and using UNC paths.
    Are you saying that, in order to know if its a network folder i have
    to search for " on " in the display name, and if its a web folder
    search for a ".", in order to determine if the difference. Is this the
    only way I could determine if its a network / web folder as compared
    to the local folders on my PC :(
    I was looking in for some kind of property that would help me determine it.I still don't understand where you want to test for this. Do you have
    a listener on the JFileChooser to catch directory changes, or did
    you set it up to only select directories, or are you talking about
    determining this after the user has chosen a file?
    No, there is no way in Java to determine whether a path that starts
    with a drive letter is in fact a mapped network folder. My suggestion
    was pretty ugly, as I said. I don't understand what you mean by "web
    folder". JFileChooser doesn't support URL paths. If you mean UNC paths
    then just test for f.getAbsolutePath().beginsWith("\\\\").
    Also why dont I see the directory structure underneath the webfolder
    or network folder from my JFileChooser?If the folder is not currently mapped because it requires a password
    or the host is not responding, then JFileChooser will display an empty
    folder. We may look into fixing this in a future release.
    One last thing: For password protected web folders, when I select them
    through my JFileChooser, the "Enter Network Password" window pops up,
    and this happens only once in the applications lifetime, I presume its
    storing this information somewhere, do you have any idea where exactly
    i should be searching for these values? I didn't see this dialog pop up from JFileChooser until the new 1.4.2
    release that we're working on. In any case, it is handled by the
    operating system and our code knows nothing about it. I'm sure there
    is no way to ask the operating system for stored passwords as that
    would compromise security.
    /Leif

  • JFilechooser Problem

    Hi,
    i have 2 problems with filechooser(jdk1.4.2)
    How can i deduct the change of Filetype in the Filechooser Combobox ,since
    i am entering some filename in the textfield of FC , if i change the File type the text inside the textfield is deleted .. i dont want to delete the text if i choose "all files " ..Can anyone suggest me how to do..?
    2.If i do some file/dir search for some letter ,the Scrolbar in List is not moving ,
    but the character is selected ..
    Regards
    Ganesan S

    You can add a PropertyChangeListener to JFileChooser and listen for JFileChooser.FILE_FILTER_CHANGED_PROPERTY events. The problem you describe is covered by the following bug report:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4678049

  • JFileChooser Win2000 Vs XP Look GUI in 1.4.1

    I observe that with 1.4.1 the JFileChooser has most of the Win 2000 File Chooser functionality, however when this same code is run on a Win XP environment I get the older(1.3.1) JFIleChooser UI, with a lot odf the functionlity (that is now provided in 1.4.1 with the 2000 env )missing.
    Please confirm that this is caused becuase the Java 1.4.1 native implementation for JFileChooser does not support XP or is this becuase I'm missing something in my code. Are there work-arounds so that the solution provides similar Look and feel in both Win2000 and Win XP.
    Thank you for your time.

    At the beginning of your main add the lines :
        public static void main(String[] args) {
                    System.setProperty("os.name", "Windows 2000");
              System.getProperty("os.version", "5.0");
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception ex) {
                   System.out.println(ex);
        }I hope this helps,
    Denis

  • JFileChooser functioning like normal Windows Apps FileChooser

    I have this problem that's been giving me too much headache already. When you click on Open on any Windows app, and click on the "Details" button, it will show you the files' details (FileName, Type, Date, etc.). This is the same with JFileChooser, so no problem there. The thing is, with Windows apps, you can click on the headers and have the files sorted according to the header you clicked. This doesn't happen to a JFileChooser. Has any of you guys did this or found any solution to this problem? I've searched (almost) everywhere, Google, Sun, etc., I even looked into JFileChooser's source code but I can't seem to find anything.
    I know this is possible, so anyone who can help, you'll be greatly appreciated.

    Thought I would pass along some updated code for this as this was very helpful to us as we are still on jdk 1.5.
    This has been modified to use the Windows UI. The advantage of doing this in the UI class is so you can set it as the default UI for JFileChooser inside your application. If you had this as a subclass of JFileChooser (as it is above) then you explicitly have to use that subclass throughout your application. By setting this UI class as the FileChooserUI in your UIDefaults table then every instance of JFileChooser will now automatically use your overridden UI and theres nothing else you have to do.
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Vector;
    import javax.swing.JComponent;
    import javax.swing.JFileChooser;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.basic.BasicDirectoryModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import com.sun.java.swing.plaf.windows.WindowsFileChooserUI;
    public class SortableFileChooserUI extends WindowsFileChooserUI {
         private DirectoryModel model;
         public static ComponentUI createUI(JComponent c) {
              return new SortableFileChooserUI((JFileChooser)c);
         public SortableFileChooserUI(JFileChooser filechooser) {
              super(filechooser);
         @Override
      protected final void createModel() {
              this.model = new DirectoryModel(getFileChooser());
          * Overridden to get our own model
          * @return
         @Override
      public final BasicDirectoryModel getModel() {
              return this.model;
          * Calls the default method then adds a MouseListener to the JTable
          * @param chooser
          * @return
         @Override
      protected final JPanel createDetailsView(JFileChooser chooser) {
              JPanel panel = super.createDetailsView(chooser);
              //Since we can't access FileChooserUI's private member detailsTable
              //directly, we have to find it in the JPanel
              final JTable tbl = findJTable(panel.getComponents());
              if (tbl != null) {
                   //Fix the columns so they can't be rearranged, if we don't do this
                   //we would need to keep track when each column is moved
                   tbl.getTableHeader().setReorderingAllowed(false);
                   //Add a mouselistener to listen for clicks on column headers
                   tbl.getTableHeader().addMouseListener(new MouseAdapter() {
                        @Override
            public void mouseClicked(MouseEvent e) {
                             //Only process single clicks
                             if (e.getClickCount() > 1) {
                return;
                             e.consume();
                             Column column = Column.getColumn(tbl.getTableHeader().columnAtPoint(e.getPoint()));
                             if ((column != null) && column.isSortable()) {
                SortableFileChooserUI.this.model.sort(tbl.getTableHeader().columnAtPoint(e.getPoint()), tbl);
              return panel;
          * Finds the JTable in the panel so we can add MouseListener
          * @param comp
          * @return
         private final JTable findJTable(Component[] comp) {
              for (int i = 0; i < comp.length; i++) {
                   if (comp[i] instanceof JTable) {
                        return (JTable)comp;
                   if (comp[i] instanceof Container) {
                        JTable tbl = findJTable(((Container)comp[i]).getComponents());
                        if (tbl != null) {
    return tbl;
              return null;
         private final static class DirectoryModel extends BasicDirectoryModel {
              private Column col = Column.FILENAME;
              private boolean ascending;
              private Comparator<File> filesizeComparator = new FilesizeComparator();
              private Comparator<File> filenameComparator = new FilenameComparator();
              private Comparator<File> filedateComparator = new FiledateComparator();
              * Must be overridden to extend BasicDirectoryModel
              * @param chooser
              protected DirectoryModel(JFileChooser chooser) {
                   super(chooser);
              * Resorts the JFileChooser table based on new column
              * @param c
              protected final void sort(int c, JTable tbl) {
                   //Set column and order
                   this.col = Column.getColumn(c);
                   this.ascending = !this.ascending;
                   String indicator = " ^";
                   if (this.ascending) {
                        indicator = " v";
                   final JTableHeader th = tbl.getTableHeader();
                   final TableColumnModel tcm = th.getColumnModel();
                   for (Column column : Column.values()) {
                        tcm.getColumn(column.getIndex()).setHeaderValue(column.getLabel());
                   final TableColumn tc = tcm.getColumn(this.col.getIndex()); // the column to change
                   tc.setHeaderValue(this.col.getLabel() + indicator);
                   th.repaint();
                   //Requery the file listing
                   validateFileCache();
              * Sorts the data based on current column setting
              * @param data
              @Override
    protected final void sort(Vector<? extends File> data) {
                   Comparator<File> comparator = null;
                   switch (this.col) {
                        case FILEDATE:
                             comparator = this.filedateComparator;
                             break;
                        case FILESIZE:
                             comparator = this.filesizeComparator;
                             break;
                        case FILENAME:
                             comparator = this.filenameComparator;
                             break;
                        default:
                             comparator = null;
                             break;
                   if (comparator != null) {
                        Collections.sort(data, comparator);
              private class FiledateComparator implements Comparator<File> {
                   public int compare(File a, File b) {
                        int ret = 1;
                        if (a.lastModified() > b.lastModified()) {
                             ret = -1;
                        else if (a.lastModified() == b.lastModified()) {
                             ret = 0;
                        if (DirectoryModel.this.ascending) {
                             ret *= -1;
                        return ret;
              private class FilesizeComparator implements Comparator<File> {
                   public int compare(File a, File b) {
                        int ret = 1;
                        if (a.length() > b.length()) {
                             ret = -1;
                        else if (a.length() == b.length()) {
                             ret = 0;
                        if (DirectoryModel.this.ascending) {
                             ret *= -1;
                        return ret;
              private class FilenameComparator implements Comparator<File> {
                   public int compare(File a, File b) {
                        if (DirectoryModel.this.ascending) {
                             return a.getName().compareToIgnoreCase(b.getName());
                        else {
                             return -1 * a.getName().compareToIgnoreCase(b.getName());
         private enum Column {
              FILENAME(0, UIManager.getString("FileChooser.fileNameHeaderText"), true),
              FILESIZE(1, UIManager.getString("FileChooser.fileSizeHeaderText"), true),
              FILETYPE(2, UIManager.getString("FileChooser.fileTypeHeaderText")),
              FILEDATE(3, UIManager.getString("FileChooser.fileDateHeaderText"), true),
              FILEATTR(4, UIManager.getString("FileChooser.fileAttrHeaderText"));
              private int index;
              private String label;
              private boolean isSortable;
              private Column(int index, String label) {
                   this(index, label, false);
              private Column(int index, String label, boolean isSortable) {
                   this.index = index;
                   this.label = label;
                   this.isSortable = isSortable;
              protected int getIndex() { return this.index; }
              protected String getLabel() { return this.label; }
              protected boolean isSortable() { return this.isSortable; }
              @Override public String toString() { return getLabel(); }
              protected static Column getColumn(int index) {
                   for (Column column : values()) {
                        if (column.getIndex() == index) {
                             return column;
                   return null;

Maybe you are looking for

  • Wont go into disk mode

    I have the Ipod Nano 6th Generation. The other day I went to power up the ipod and it would not switch on. Eventually I got just a white screen and this is all it does. I have done a restore through I Tunes and this has not done anything. Also when h

  • WAP2000 PoE/VLANs loosing Config

    Hello everybody, i have 4 WAP2000 configured with VLAN (sure one for management) connected to an linksys srw244g4p poe switch. I can configure the APs and even with the VLAN Setup they are working fine. I can access them connected to an trunk port an

  • Oracle 10g Workshop I or Oracle 11g workshop I

    Hi guys, I need a bit of advice on which course should I follow. I know that Oracle 11g is the latest release and it composes of new features compared to 10g, but I need to know the which is worth doing is 10g or 11g. -Coz I heard that oracle 11g sti

  • Toshiba TL515U Series - Questions

    I just bought the 47" version of this TV and it's simply amazing. I've heard about the CEVO engine a long time ago and this TV just screams quality. I freaking love it even though it's refurbished. I would like to ask a few questions though: 1. I've

  • NPE starting Visual Administrator.

    I have a new install of R3 Enterprise 4.7 and have added J2EE.  Everything is working for me (interact with SAP GUI, browse to the J@EE Start page, etc) except that I get an NPE when invoking the Visual Administrator to install the license.  There's