JFileChooser as a JComponent

I've added a JFileChooser to a panel and disabled the standard control buttons (as they would conflict with the general feel of my application, which has a "next" button elsewhere). I want to be notified when the user selects a file and I have attached a PropertyChangeListener accordingly. I have but one problem.
If I simply type a filename into the text field, no change event is fired. I must press the enter key in the text field for the change to take effect. It seems that what I need is a way to actively request that the JFileChooser update its selected file based on the contents of the filename text field. How might I do this?
(The only solution I have so far is something like:
JFileChooser chooser = ...;
((BasicFileChooserUI)(chooser.getUI())).getApproveSelectionAction().actionPerformed(new ActionEvent(...));which is ugly on so many levels...)

I've added a JFileChooser to a panel and disabled the standard control buttons (as they would conflict with the general feel of my application, which has a "next" button elsewhere). I want to be notified when the user selects a file and I have attached a PropertyChangeListener accordingly. I have but one problem.
If I simply type a filename into the text field, no change event is fired. I must press the enter key in the text field for the change to take effect. It seems that what I need is a way to actively request that the JFileChooser update its selected file based on the contents of the filename text field. How might I do this?
(The only solution I have so far is something like:
JFileChooser chooser = ...;
((BasicFileChooserUI)(chooser.getUI())).getApproveSelectionAction().actionPerformed(new ActionEvent(...));which is ugly on so many levels...)

Similar Messages

  • JFileChooser and JFrame

    Does anyone know if it's possible to place a jFileChooser in a frame ... and make it work?
    I need 2 file choosers placed in a frame. I have to be able to access the selected directories and files.
    Suggestions?

    JFileChooser is a JComponent.. you may add it to any Container extended class:
    import java.awt.*;
    import javax.swing.*;
    * to  JoAnn Lemm
    * @author courtesy by Felipe Ga�cho
    public class Clipped extends JFrame
         // You may create another type of file choosers, including specific directories
         // listing, etc.
         JFileChooser chooser1 = new JFileChooser();
         JFileChooser chooser2 = new JFileChooser();
         static public void main(String[] args)
              new Clipped();
         Clipped()
              super();
              getContentPane().setLayout(new GridLayout(1,2,15,2));
              getContentPane().add(chooser1);
              getContentPane().add(chooser2);
              pack();
              setVisible(true);
    }

  • JFileChooser is a very nasty thing

    Greetings,
    Fiddling with JFileChooser objects I noticed a couple of peculiarities:
    1) The 'Cancel' button text cannot be changed by the user
    2) The text next to the selected file cannot be changed
    3) The text next to the file filter cannot be changed.
    I can remove most of the controls (as a result to an old question of
    mine for which very satisfactory and fine answers were posted).
    What's up with that component? Did it go through any design at all or
    was it conceived while the programmer was sniffing cheap glue?
    IMHO that JFileChooser thing is a total inconsistent mess. Does anyone
    know whether or not better alternatives are available or should I write
    my own localizable, modifiable version?
    kind regards,
    Jos

    Jos!That's me! ;-)
    [ snippety ... ]
    The farthest I got was finding the method that
    actually returns the dialog:[ snipped the createDialog method ]
    Where are all the components actually getting put together and drawn?Not in that method; that's for sure. Don't forget that a JFileChooser
    extends a JComponent and that's where all the other components are
    stored. For now I localize all the text components in this JFileChooser
    by 'put'ing the following keys in the UIManager:FileChooser.lookInLabelText
    FileChooser.filesOfTypeLabelText
    FileChooser.upFolderToolTipText
    FileChooser.fileNameLabelText
    FileChooser.homeFolderToolTipText
    FileChooser.newFolderToolTipText
    FileChooser.listViewButtonToolTipTextlist
    FileChooser.detailsViewButtonToolTipText
    FileChooser.saveButtonText=Save
    FileChooser.openButtonText=Open
    FileChooser.cancelButtonText=Cancel
    FileChooser.updateButtonText=Update
    FileChooser.helpButtonText=Help
    FileChooser.saveButtonToolTipText=Save
    FileChooser.openButtonToolTipText=Open
    FileChooser.cancelButtonToolTipText=Cancel
    FileChooser.updateButtonToolTipText=Update
    FileChooser.helpButtonToolTipText=HelpI found those key strings by googling and scrutinizing sources. On top of
    that I can show/hide those toolbars (and their buttons and stuff) like this:     private void hideComponents(Component[] components, boolean visible) {
              for (int i= 0; i < components.length; i++) {
                   if (components[i] instanceof JPanel)
                        hideComponents(((JPanel)components).getComponents(), visible);
                   else if (components[i] instanceof JToolBar)
                        components[i].setVisible(visible);
    IMHO that JFileChooser API is a mess and far from complete. I'm afraid
    I'll find the same mess when I put my teeth in the JColorChooser thingy ;-)
    kind regards,
    Jos

  • How To use JFile Chooser in a Tabbed Pane Dialog

    I have created a tabbed pane dialog. In one of the tabs I want to add a JFile Chooser.
    How can I approach this problem. also Do I have to use a JDialog with a frame or can I create a JDialog without using a frame and create a instance from the main function.

    I have created a tabbed pane dialog. In one of the
    tabs I want to add a JFile Chooser. Since JFileChooser is a JComponent you could add it to any Container like any other JComponent.
    Maybe you have to do some init by hand which is done normally by the show*() methods of JFileChooser. Taking a look at the source of showDialog() should help.
    Hope that helps,
    Alex

  • Trying to scroll a JComponent with JScrollPane but can't do it. :(

    Hi, what im trying to do seems to be simple but I gave up after trying the whole day and I beg you guys help.
    I created a JComponent that is my map ( the map consists only in squared cells ). but the map might be too big for the screen, so I want to be able to scroll it. If the map is smaller than the screen,
    everything works perfect, i just add the map to the frame container and it shows perfect. But if I add the map to the ScrollPane and them add the ScrollPane to the container, it doesnt work.
    below is the code for both classes Map and the MainWindow. Thanks in advance
    package main;
    import java.awt.Color;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowStateListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    public class MainWindow implements WindowStateListener {
         private JFrame frame;
         private static MainWindow instance = null;
         private MenuBar menu;
         public Map map = new Map();
         public JScrollPane Scroller =
              new JScrollPane( map,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         public JViewport viewport = new JViewport();
         private MainWindow(int width, int height) {
              frame = new JFrame("Editor de Cen�rios v1.0");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setVisible(true);
              menu = MenuBar.createMenuBar();
              JFrame.setDefaultLookAndFeelDecorated(false);
              frame.setJMenuBar(menu.create());
              frame.setBackground(Color.WHITE);
              frame.getContentPane().setBackground(Color.WHITE);
                                    // HERE IS THE PROBLEM, THIS DOESNT WORKS   <---------------------------------------------------------------------------------------
              frame.getContentPane().add(Scroller);
              frame.addWindowStateListener(this);
    public static MainWindow createMainWindow(int width, int height)
         if(instance == null)
              instance = new MainWindow(width,height);
              return instance;               
         else
              return instance;
    public static MainWindow returnMainWindow()
         return instance;
    public static void main(String[] args) {
         MainWindow mWindow = createMainWindow(800,600);
    public JFrame getFrame() {
         return frame;
    public Map getMap(){
         return map;
    @Override
    public void windowStateChanged(WindowEvent arg0) {
         map.repaint();
    package main;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import javax.swing.Scrollable;
    public class Map extends JComponent  implements Scrollable{
         private Cell [] mapCells;
         private String mapPixels;
         private String mapAltura;
         private String mapLargura;
         public void createMap(String pixels , String altura, String largura)
              mapPixels = pixels;
              mapAltura = altura;
              mapLargura = largura;
              int cells = Integer.parseInt(altura) * Integer.parseInt(largura);
              mapCells = new Cell[cells];
              //MainWindow.returnMainWindow().getFrame().getContentPane().add(this);
              Graphics2D grafico = (Graphics2D)getGraphics();
              for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                   mapCells[i] = new Cell( horiz, vert,Integer.parseInt(mapPixels));
                   MainWindow.returnMainWindow().getFrame().getContentPane().add(mapCells);
                   grafico.draw(mapCells[i].r);
                   horiz = horiz + Integer.parseInt(mapPixels);
                   if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                        horiz = 0;
                        vert = vert + Integer.parseInt(mapPixels);
              repaint();
         @Override
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              System.out.println("entrou");
              Graphics2D g2d = (Graphics2D)g;
              if(mapCells !=null)
                   for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                        g2d.draw(mapCells[i].r);
                        horiz = horiz + Integer.parseInt(mapPixels);
                        if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                             horiz = 0;
                             vert = vert + Integer.parseInt(mapPixels);
         @Override
         public Dimension getPreferredScrollableViewportSize() {
              return super.getPreferredSize();
         @Override
         public int getScrollableBlockIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;
         @Override
         public boolean getScrollableTracksViewportHeight() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public boolean getScrollableTracksViewportWidth() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public int getScrollableUnitIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;

    Im so sorry Darryl here are the other 3 classes
    package main;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.filechooser.FileNameExtensionFilter;
    public class MenuActions {
         public void newMap(){
              final JTextField pixels = new JTextField(10);
              final JTextField hCells = new JTextField(10);
              final JTextField wCells = new JTextField(10);
              JButton btnOk = new JButton("OK");
              final JFrame frame = new JFrame("Escolher dimens�es do mapa");
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
              btnOk.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
              String txtPixels = pixels.getText();
              String hTxtCells = hCells.getText();
              String wTxtCells = wCells.getText();
              frame.dispose();
              MainWindow.returnMainWindow().map.createMap(txtPixels,hTxtCells,wTxtCells);         
              frame.getContentPane().add(new JLabel("N�mero de pixels em cada c�lula:"));
              frame.getContentPane().add(pixels);
              frame.getContentPane().add(new JLabel("Altura do mapa (em c�lulas):"));
              frame.getContentPane().add(hCells);
              frame.getContentPane().add(new JLabel("Largura do mapa (em c�lulas):"));
              frame.getContentPane().add(wCells);
              frame.getContentPane().add(btnOk);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(300, 165);
              frame.setResizable(false);
             frame.setVisible(true);
         public Map openMap (){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showOpenDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: manipular o mapa aberto
              return new Map();          
         public void save(){
         public void saveAs(){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showSaveDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: Salvar o mapa aberto
         public void exit(){
              System.exit(0);          
         public void copy(){
         public void paste(){
    package main;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    public class MenuBar implements ActionListener{
         private JMenuBar menuBar;
         private final Color color = new Color(250,255,245);
         private String []menuNames = {"Arquivo","Editar"};
         private JMenu []menus = new JMenu[menuNames.length];
         private String []arquivoMenuItemNames = {"Novo","Abrir", "Salvar","Salvar Como...","Sair" };
         private KeyStroke []arquivoMenuItemHotkeys = {KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_A,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.SHIFT_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.ALT_MASK)};
         private JMenuItem []arquivoMenuItens = new JMenuItem[arquivoMenuItemNames.length];
         private String []editarMenuItemNames = {"Copiar","Colar"};
         private KeyStroke []editarMenuItemHotKeys = {KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK),
                                                                 KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK)};
         private JMenuItem[]editarMenuItens = new JMenuItem[editarMenuItemNames.length];
         private static MenuBar instance = null;
         public JMenuItem lastAction;
         private MenuBar()
         public static MenuBar createMenuBar()
              if(instance == null)
                   instance = new MenuBar();
                   return instance;                    
              else
                   return instance;
         public JMenuBar create()
              //cria a barra de menu
              menuBar = new JMenuBar();
              //adiciona items a barra de menu
              for(int i=0; i < menuNames.length ; i++)
                   menus[i] = new JMenu(menuNames);
                   menuBar.add(menus[i]);
              //seta a hotkey da barra como F10
              menus[0].setMnemonic(KeyEvent.VK_F10);
              //adiciona items ao menu arquivo
              for(int i=0; i < arquivoMenuItemNames.length ; i++)
                   arquivoMenuItens[i] = new JMenuItem(arquivoMenuItemNames[i]);
                   arquivoMenuItens[i].setAccelerator(arquivoMenuItemHotkeys[i]);
                   menus[0].add(arquivoMenuItens[i]);
                   arquivoMenuItens[i].setBackground(color);
                   arquivoMenuItens[i].addActionListener(this);
              //adiciona items ao menu editar
              for(int i=0; i < editarMenuItemNames.length ; i++)
                   editarMenuItens[i] = new JMenuItem(editarMenuItemNames[i]);
                   editarMenuItens[i].setAccelerator(editarMenuItemHotKeys[i]);
                   menus[1].add(editarMenuItens[i]);
                   editarMenuItens[i].setBackground(color);
                   editarMenuItens[i].addActionListener(this);
              menuBar.setBackground(color);
              return menuBar;                    
         @Override
         public void actionPerformed(ActionEvent e) {
              lastAction = (JMenuItem) e.getSource();
              MenuActions action = new MenuActions();
              if(lastAction.getText().equals("Novo"))
                   action.newMap();
              else if(lastAction.getText().equals("Abrir"))
                   action.openMap();
              else if(lastAction.getText().equals("Salvar"))
                   action.save();               
              else if(lastAction.getText().equals("Salvar Como..."))
                   action.saveAs();               
              else if(lastAction.getText().equals("Sair"))
                   action.exit();               
              else if(lastAction.getText().equals("Copiar"))
                   action.copy();               
              else if(lastAction.getText().equals("Colar"))
                   action.paste();               
    package main;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    public class Cell extends JComponent{
         public float presSub = 0;
         public double errPressInfer = 0.02;
         public double errPressSup = 0.02;
         public float profundidade = 1;
         public Rectangle2D r ;
         public Cell(double x, double y, double pixel)
              r = new Rectangle2D.Double(x,y,pixel,pixel);          
    Edited by: xnunes on May 3, 2008 6:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JFileChooser animated gif preview

    I'm using an Accesory with an ImageIcon to preview images on a JFileChooser.
    It works ok, but I would like to know how do I get those animated gif to restart their animation whenever I click some other file (so the image preview goes to null) and click back on them.
    There are non-looped gifs and looped ones, it is specially for the non-looped gifs as to give a way to get to see the animation again. After clicking the file once the animation never plays again, even if a load another preview by clicking another file and then go back...
    Since there's no obvious method on ImageIcon or Image I tried flush since it says it clears the data but the only thing I got was the gif animating improperly (it would get trash/noise).
    * JFileChooserImagePreview.java
    * Created on 16 de junio de 2005, 12:58 AM
    package ptcg.win.util;
    import javax.swing.*;
    import java.beans.*;
    import java.awt.*;
    import java.io.File;
    /* from FileChooserDemo2.java. */
    public class JFileChooserImagePreview extends javax.swing.JComponent implements PropertyChangeListener {
         public JFileChooserImagePreview(JFileChooser fc) {
              setHeight = -1;
              setWidth = -1;
              setPreferredSize(new Dimension(100, 50));
              fc.addPropertyChangeListener(this);
         public JFileChooserImagePreview(JFileChooser fc, int setHeight, int setWidth) {
              this.setHeight = setHeight;
              this.setWidth = setWidth;
              setPreferredSize(new Dimension(setHeight, setWidth));
              fc.addPropertyChangeListener(this);
         public void propertyChange(PropertyChangeEvent e) {
              boolean update = false;
              String prop = e.getPropertyName();
              //If the directory changed, don't show an image.
              if(JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                   file = null;
                   update = true;
              } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
                   file = (File) e.getNewValue();
                   update = true;
              //Update the preview accordingly.
              if (update) {
                   thumbnail = null;
                   if(isShowing()) {
                        loadImage();
                        repaint();
         public void loadImage() {
              if (file == null) {
                   thumbnail = null;
                   return;
              ImageIcon tmpIcon = new ImageIcon(file.getPath());
              if (tmpIcon != null) {
                   Image i = tmpIcon.getImage();
                   //i.flush(); //screws the animation
                   thumbnail = new ImageIcon(i.getScaledInstance(setHeight, setWidth, Image.SCALE_SMOOTH));
         protected void paintComponent(Graphics g) {
              if (thumbnail == null) {
                   loadImage();
              if (thumbnail != null) {
                   int x = getWidth()/2 - thumbnail.getIconWidth()/2;
                   int y = getHeight()/2 - thumbnail.getIconHeight()/2;
                   if (y < 0) {
                        y = 0;
                   if (x < 5) {
                        x = 5;
                   thumbnail.paintIcon(this, g, x, y);
         ImageIcon thumbnail = null;
         File file = null;
         int setHeight, setWidth;
    }Thanks in advance

    Never-mind. I have it working properly now.

  • How to close JFileChooser dialog only while using ESC key ?

    Hi All,
    I am using a Frame and from this frame i am calling the JFileChooser via a JButton.
    and using JFileChooser ShowOpenDialog() for open and close .
    while doing ESC operation my Main Frame is getting closed with JFileChooser dialog.
    Can i close only JFileChooser dialog while doing ESCAPE key operation.
    I Have Escape key function in Main Frame file and JFileChooser file( EscKeyEventActionIntialization)
    But while debuging i am not able to catch the esc key action inside EscKeyEventActionIntialization.
    I have attached the code, please suggest me , if i need to do any change .
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package MainPackage;
    import javax.swing.filechooser.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    public class SourceSettings extends javax.swing.JDialog{
        JDialog dialog;
        private javax.swing.JFileChooser jFileChooser1;
        MainFile  mainFile;
        ImageIcon icon = new ImageIcon(getClass().getResource("/Resource/mchpIcon.GIF"));
        /** Creates new form SourceSetting */
        public SourceSettings(MainFile  pMPFS) {
            dialog = new JDialog();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            mainFile = pMPFS;
            jFileChooser1 = new javax.swing.JFileChooser();
            dialog.add(jFileChooser1);
            EscKeyEventActionIntialization();
            jFileChooser1.setDialogTitle("Browse For Folder");
            jFileChooser1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 11)); // NOI18N
            jFileChooser1.setName("Browse For Folder"); // NOI18N
        public String getDirctoryPath()
            int retval = jFileChooser1.showOpenDialog(dialog);
            dialog.setVisible(true);
            if(retval  == JFileChooser.APPROVE_OPTION)
                return jFileChooser1.getSelectedFile().getAbsolutePath().toString();
            else
                dialog.setVisible(false);
                dialog.dispose();
                return null;
        public String getParentDirctoryPath()
            return jFileChooser1.getCurrentDirectory().getAbsolutePath().toString();
        public String getOutputDirctoryPath()
            if(jFileChooser1.showOpenDialog(mainMpfs)  == JFileChooser.APPROVE_OPTION)
               return jFileChooser1.getCurrentDirectory().getAbsolutePath().toString();
            else
               dialog.dispose();
               return null;
        private void EscKeyEventActionIntialization()
            Action  ESCactionListener = new AbstractAction () {
              public void actionPerformed(ActionEvent actionEvent) {
                dialog.setVisible(false);
                dialog.dispose();
            KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true);
            JComponent comp = dialog.getRootPane();
            comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "ESCAPE");
            ActionMap actionMap = comp.getActionMap();
            actionMap.put("ESCAPE", ESCactionListener);
    }

    You have a class that extends JDialog and has a JDialog member variable (very confusing), and no main(...) method. How is the class used as a JDialog?
    To get better help sooner, post a SSCCE that clearly demonstrates your problem. Note that this should be executable and should not contain any extraneous code.
    db

  • Applet with JFilechooser called from a Javascript blocks paint messages

    Hi,
    I am trying to create an applet that can:
    1) be called from a Javascript
    2) displays a file selection dialog for multi-selecting files
    3) returns the selected filenames in a string to the JavaScript
    I am able to use doPrivileged to apply the necessary security context to launch a JFilechooser and return the filenames selected. However, When the JFilechooser dialog is visible and the user moves the dialog window around the HTML pages dose not receive any repaint messages. They seem to be blocked by the thread that launched the JFilechooser dialog and is probably blocking update events as the dialog is still visible.
    I know I need some type of a message pump so the child thread can inform the parent thread and the browser to repaint. However, I don't know how to do this.
    Please help.
    ------Applet Code Begin:-----
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.AWTEvent;
    import java.awt.event.AWTEventListener.*;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.util.Locale;
    import java.util.MissingResourceException;
    import java.util.Properties;
    import java.util.ResourceBundle;
    import java.util.Vector;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    public class SampleApplet extends JApplet
       boolean allowDirs=false;
       boolean allowFiles=true;
       boolean hidden=false;
       File lastUserDir=null;
       public void init()
        public void start()
        public void stop()
        public String selectFiles()
           String choosenFiles = null;
           choosenFiles = new String((String)java.security.AccessController.doPrivileged(
           new java.security.PrivilegedAction()
         public Object run()
            String choosenFiles=new String();
                 JFilechooser fc = new JFilechooser();
         fc.setFileSelectionMode(allowDirs ? (allowFiles ? JFileChooser.FILES_AND_DIRECTORIES
            : JFileChooser.DIRECTORIES_ONLY)
            : JFileChooser.FILES_ONLY);
         fc.setMultiSelectionEnabled(true);
                 int returnVal = fc.showOpenDialog(null);
                 if (returnVal == JFileChooser.APPROVE_OPTION)
                    choosenFiles = "The selected filesnames will be stuffed here";
              return choosenFiles; //return whatever you want
           return choosenFiles;   
    ------Applet Code End:-----
    ------Html Code Begin:-----
    <html>
    <applet id="SampleApplet" archive="SampleApplet.jar"; code="SampleApplet.class"; width="2" height="2" codebase=".">
    </applet>
    <head>
        <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
    function SelectFiles_onclick()
      var s = (document.applets[0].selectFiles());
      alert(s);
    </script>
    </head>
    <body>
        Click Test button to select files
        <input id="SelectFiles" type="button" value="Select Files" onclick="return SelectFiles_onclick()" />
    </body>
    </html>
    ------Html Code End:-----

    try this:
    first don't open the file dialog in the SelectFiles call. Start a new thread that does that. Then return from the SelectFiles call immediately. Now after the user selectes the files call back into the javascript by doing something like this:
    pass the list of files into this function, each on being a String in the params array
        public synchronized void sendDataToUI(Object[] params) {
            if (FuserState.hasQuit()) {
                return;
            String function = "getUpdates";
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "Calling Javascript function " + function);
            if (getJavaScriptWindow() == null) {
                logger.log(Level.SEVERE, "Member javascriptWindow is NULL, no call was made!");
                return;
            try {
                getJavaScriptWindow().call(function, params);
            catch (netscape.javascript.JSException x) {
                if (params == null) {
                    logger.log(Level.SEVERE, "p=NULL PARAM");
                } else {
                    logger.log(Level.SEVERE, "p=" + params[0]);
        protected JSObject getJavaScriptWindow() {
            javascriptWindow = JSObject.getWindow(this);
        }

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

  • Strange (Nullpointer) Excep. during Eventdispatching (JFileChooser).

    Hi, sometimes I receive this (complete) stack trace (see below).
    It seems do appear at random, even if no JFilechooser is opened. During initialization of my program there are created some instances of JFilechooser, but I can't figure out what the problem is.
    Cause I taught the setFileSelected action would only take place if you open a Filechooser. But it has been raised, even if there had never been any Filechooser open.
    The first time I received this I thought, it would be an error of the jvm, but then the same error reappeared more than once.
    I'm using the 1.4.1_01 jre.
    It seems to be a problem with the event queue, but what is going wrong.
    Has anyone has ever faced such a problem and can give any clue or idea, how to fix it?
    Any help appreciated.
    Thanks a lot in advance.
    Greetings Michael
    java.lang.NullPointerException
         at javax.swing.plaf.metal.MetalFileChooserUI.setFileSelected(Unknown Source)
         at javax.swing.plaf.metal.MetalFileChooserUI$DelayedSelectionUpdater.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

    Hi Leif,
    Hi Michael,
    It could be one of these bugs that are still open:
    http://developer.java.sun.com/developer/bugParade/bugs/4822786.html (no tripple-clicking)
    http://developer.java.sun.com/developer/bugParade/bugs/4759922.html (no file deletion)
    I've read them, but none of them matches my problem exactly.
    If neither of these matches your problem, could you post >a stack trace?The number is changing randomly.
    java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9
        at java.util.Vector.get(Unknown Source)
        at javax.swing.plaf.basic.BasicDirectoryModel.getElementAt(Unknown Source)
        at javax.swing.plaf.basic.BasicListUI.updateLayoutState(Unknown Source)
        at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(Unknown Source)
        at javax.swing.plaf.basic.BasicListUI.getCellBounds(Unknown Source)
        at javax.swing.JList.getCellBounds(Unknown Source)
        at javax.swing.JList.ensureIndexIsVisible(Unknown Source)
        at javax.swing.plaf.metal.MetalFileChooserUI.ensureIndexIsVisible(Unknown Source)
        at javax.swing.plaf.metal.MetalFileChooserUI.doDirectoryChanged(Unknown Source)
        at javax.swing.plaf.metal.MetalFileChooserUI.access$2600(Unknown Source)
        at javax.swing.plaf.metal.MetalFileChooserUI$12.propertyChange(Unknown Source)
        at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(Unknown Source)
        at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(Unknown Source)
        at javax.swing.JComponent.firePropertyChange(Unknown Source)
        at javax.swing.JFileChooser.setCurrentDirectory(Unknown Source)
        at de.gruenewald.michael.PartyJukebox.PlayList.initFileChoosers(PlayList.java:192)
        at de.gruenewald.michael.PartyJukebox.PlayList.<init>(PlayList.java:96)
        at de.gruenewald.michael.PartyJukebox.PlayList.getReference(PlayList.java:148)
        at de.gruenewald.michael.PartyJukebox.GUI.<init>(GUI.java:91)
        at de.gruenewald.michael.PartyJukebox.GUI.main(GUI.java:217)The Filechooser isn't visible and this exception is risen
    during the startup of the Gui (No clicking!). It occurs very seldom at the start of my app.
    Perhaps this may be caused, by the fileFilters. There may be less files visible than stored in the dir.
    So perhaps some additional code for checking this out could fix this problem.
    Do you mean that you are getting the exception even when >using
    invokeLater()?No, invokeLater uses a Thread and Exception raised their aren't displayed or logged normally, So I can't tell you , if this really solves the problem or if it is just hidden.
    By the way I'm catching the Event-Dispatching-thread, with:
    System.setProperty("sun.awt.exception.handler",HandleAllExceptionOfEventDispatching.class.getName());    I try to use a ThreadLoggingGrooup for the scheduled Thread and will tell you about the results here later (cause of the Exception is really seldom raised.)
    I will also use try to use it for the first problem (NullPointerExcep.).
    SwingUtilities.invokeLater(new Thread(RuntimeObjects.getReference().getLoggingThreadGroup() ,new Runnable(){
                ConfigData config = ConfigData.getReference();
                public void run(){
                    if ( config.getDefaultDirForPlayLists() != null){
                        File file = new File(config.getDefaultDirForPlayLists());
                        if( file.exists() && file.canRead() && file.isDirectory() ){
                            PlayList.this.load.setCurrentDirectory(file);
                            PlayList.this.save.setCurrentDirectory(file);
    public ThreadGroup getLoggingThreadGroup(){
            loggingThreadGroup = new ThreadGroup("LoggingForThreads"){
                PrintStream errLog = RuntimeObjects.getReference().getErrorLog();
                public void uncaughtException(Thread t, Throwable e){
                    if (!(e instanceof ThreadDeath) ){
                        if ( errLog == null){ 
                            errLog.println(e.getMessage());
                            e.printStackTrace(errLog);
                        e.printStackTrace();
            return loggingThreadGroup;
        } Cheers,
    /LeifI also post my initFileChoosers:
    private void initFileChoosers(){
            load = new JFileChooser();
            save = new JFileChooser();
            AllPlaylistsFilter all = new AllPlaylistsFilter();
            PlayListFilter playFilter = new PlayListFilter();
            PlsFilter plsFilter = new PlsFilter();
            M3uFilter m3u = new M3uFilter();
            //save.removeChoosableFileFilter(save.getFileFilter());
            //load.removeChoosableFileFilter(load.getFileFilter());
            save.setAcceptAllFileFilterUsed(false);
            load.setAcceptAllFileFilterUsed(false);
            load.addChoosableFileFilter(all);
            load.addChoosableFileFilter(playFilter);
            load.addChoosableFileFilter(plsFilter);
            load.addChoosableFileFilter(m3u);
            save.addChoosableFileFilter(all);
            save.addChoosableFileFilter(playFilter);
            save.addChoosableFileFilter(plsFilter);
            save.addChoosableFileFilter(m3u);
            JCheckBox relativePaths = new JCheckBox(rb.getString("CheckBox.RelativePaths"),false);
            save.setAccessory(relativePaths);
            load.setFileFilter(all);
            save.setFileFilter(all);
            //SwingUtilities.invokeLater(new Runnable(){
            //    ConfigData config = ConfigData.getReference();
            //    public void run(){
                    if ( config.getDefaultDirForPlayLists() != null){
                        File file = new File(config.getDefaultDirForPlayLists());
                        if( file.exists() && file.canRead() && file.isDirectory() ){
                            PlayList.this.load.setCurrentDirectory(file);
                            PlayList.this.save.setCurrentDirectory(file);
           }Example of a FileFilter:
    abstract class DefaultFileFilter extends javax.swing.filechooser.FileFilter{
        public String getExtension(){ return ".ppl"; }
    class AllPlaylistsFilter extends DefaultFileFilter{
         public boolean accept(File pathname) {
            if ( pathname.isDirectory() ) return true;
            String name = pathname.getPath();
            int pos = name.lastIndexOf('.');
            String extension = name.substring(pos+1);
            if ( extension.equalsIgnoreCase("m3u") || extension.equalsIgnoreCase("pls") || extension.equalsIgnoreCase("ppl") ) return true;
            return false;
         public String getDescription(){ return "All Playlists"; }
         public String getExtension(){ return ".m3u"; }
    }Cheers Michael

  • NullPointerException in JFileChooser.showOpenDialog() JRE 1.7

    Hi all,
    In my application, i have used JFileChooser to select a file. When i try to open JFileChooser.showOpenDialog() it throws the following exception. Not sure where i am wrong. Please help me.
    Exception:
    #Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    # at sun.awt.shell.Win32ShellFolder2.access$200(Unknown Source)
    # at sun.awt.shell.Win32ShellFolder2$1.call(Unknown Source)
    # at sun.awt.shell.Win32ShellFolder2$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.runWorker(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)
    Source Code:
         public File browseFile() {
              UIManager.put("FileChooser.readOnly", Boolean.TRUE);
              if (DEBUG > 4) {
                   System.out.println("Initial Dir : " + initialDir);
                   System.out.println("Title : " + title);
              JFileChooser jfc = new JFileChooser();
              FileFilter filter = null;
              if (null != extension && extension.trim().length() > 0) {
                   if (null != description && description.trim().length() > 0) {
                        filter = new ExtensionFilter(this.description, this.extension);
                   } else {
                        filter = new ExtensionFilter(this.extension, this.extension);
                   jfc.setFileFilter(filter);
              if (null != title && title.trim().length() > 0) {
                   jfc.setDialogTitle(title);
              if (null != initialDir) {
                   jfc.setCurrentDirectory(new File(initialDir));
              int returnVal = - 1;
              if (type == JFileChooser.OPEN_DIALOG) {
                   returnVal = jfc.showOpenDialog(this);
              } else if (type == JFileChooser.SAVE_DIALOG) {
                   returnVal = jfc.showSaveDialog(this);
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = jfc.getSelectedFile();
                   setVisible(false);
                   return file;
              } else {
                   setVisible(false);
                   return null;
    Thanks for all in Advance.
    /dhavan

    Sorry, actually i commented that line. Here is the updated code.
         public File browseFile() {
              parent = this;
              UIManager.put("FileChooser.readOnly", Boolean.TRUE);
    //          if (DEBUG > 4) {
                   System.out.println("Initial Dir : " + initialDir);
                   System.out.println("Initial File : " + initialFile);
                   System.out.println("Title : " + title);
              try {
                   EventQueue.invokeLater( new Runnable() {
                        public void run() {
                             jfc = new JFileChooser();
                             FileFilter filter = null;
                             if (null != extension && extension.trim().length() > 0) {
                                  if (null != description && description.trim().length() > 0) {
                                       filter = new ExtensionFilter(description, extension);
                                  } else {
                                       filter = new ExtensionFilter(extension, extension);
                                  jfc.setFileFilter(filter);
                             if (null != title && title.trim().length() > 0) {
                                  jfc.setDialogTitle(title);
                             if (null != initialDir) {
                                  jfc.setCurrentDirectory(new File(initialDir));
                        if (type == JFileChooser.OPEN_DIALOG) {
                             System.out.println("JFileChooser.OPEN_DIALOG");
                             returnVal = jfc.showOpenDialog(parent);
                        } else if (type == JFileChooser.SAVE_DIALOG) {
                             System.out.println("JFileChooser.SAVE_DIALOG");
                             returnVal = jfc.showSaveDialog(parent);
              } catch (Exception ex) {
                   ex.printStackTrace();
              return null;
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = jfc.getSelectedFile();
                   return file;
              } else {
                   return null;
         }Exception:-
    #Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    #     at sun.awt.shell.Win32ShellFolderManager2.createShellFolder(Unknown Source)
    #     at sun.awt.shell.Win32ShellFolderManager2.getRecent(Unknown Source)
    #     at sun.awt.shell.Win32ShellFolderManager2.get(Unknown Source)
    #     at sun.awt.shell.ShellFolder.get(Unknown Source)
    #     at sun.swing.WindowsPlacesBar.<init>(Unknown Source)
    #     at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.updateUseShellFolder(Unknown Source)
    #     at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.installComponents(Unknown Source)
    #     at javax.swing.plaf.basic.BasicFileChooserUI.installUI(Unknown Source)
    #     at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.installUI(Unknown Source)
    #     at javax.swing.JComponent.setUI(Unknown Source)
    #     at javax.swing.JFileChooser.updateUI(Unknown Source)
    #     at javax.swing.JFileChooser.setup(Unknown Source)
    #     at javax.swing.JFileChooser.<init>(Unknown Source)
    #     at javax.swing.JFileChooser.<init>(Unknown Source)
    #     at com.marimba.ncp.apps.editor.SwingFileChooser$1.run(SwingFileChooser.java:59)
    #     at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    #     at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    #     at java.awt.EventQueue.access$000(Unknown Source)
    #     at java.awt.EventQueue$1.run(Unknown Source)
    #     at java.awt.EventQueue$1.run(Unknown Source)
    #     at java.security.AccessController.doPrivileged(Native Method)
    #     at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    #     at java.awt.EventQueue.dispatchEvent(Unknown Source)
    #     at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    #     at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    #     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    #     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    #     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    #     at java.awt.EventDispatchThread.run(Unknown Source)

  • A column "name" from  JFileChooser

    Hi all,
    I want to overwrite the sorting method of names of files in JFileChooser. How can I get a column &#8220;name&#8221; from JFileChooser?
    Thanks

    Couldn't help but toying around. Here are two ways to get it working. But you have to target a specific L&F.
    package test;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.plaf.metal.*;
    import javax.swing.filechooser.*;
    * @author  futt
    public class CustomFileChooser {
        private CustomFileChooser(){}
        //this is for variant two
        public static class MetalChooserUIThatSortsBySize
        extends MetalFileChooserUI
            public MetalChooserUIThatSortsBySize(JFileChooser f){
                super(f);
            private BasicDirectoryModel model;
            protected void createModel() {
                model = new DirectoryModel(getFileChooser(), c);
            public BasicDirectoryModel getModel(){
                return model;
            final Comparator c = new Comparator(){
                private FileSystemView
                    fsv = FileSystemView.getFileSystemView()
                private boolean ignoreLength(File f){
                    //avoid calls to isDirectory for FileSystemRoots and the like.
                    //may need some tweaking
                    if( fsv.isFileSystemRoot(f) )
                        return true;
                    if( f.isDirectory() )
                        return true;
                    return false;
                public int compare(Object o1, Object o2){
                    File f1 = (File)o1, f2 = (File)o2; //ClassCast
                    if( ignoreLength(f1) ) return -1;
                    if( ignoreLength(f2) ) return 1;
                    return (int) (f1.length() - f2.length());
            public static ComponentUI createUI(JComponent c){
                if( c instanceof JFileChooser){
                    return new MetalChooserUIThatSortsBySize((JFileChooser)c);
                else {
                    return null;
        public static JFileChooser createMetalFileChooser(Comparator sorter){
            return new MetalChooser(sorter);
        //this is for variant one
        static class MetalChooser
        extends JFileChooser
            public MetalChooser(final Comparator c){
                super();
                setUI(
                    new MetalFileChooserUI(null){
                        private BasicDirectoryModel model;
                        protected void createModel() {
                            model = new DirectoryModel(MetalChooser.this, c);
                        public BasicDirectoryModel getModel(){
                            return model;
        private static class DirectoryModel
        extends BasicDirectoryModel
            private final Comparator
                sorter
            public DirectoryModel(JFileChooser f, Comparator c){
                super(f);
                sorter = c;
            protected void sort(Vector v){
                if( sorter != null ){
                    Collections.sort(v, sorter);
                else {
                    super.sort(v);
        //this is the variant one.
        //unfortunately, it seems to shredder the rendering a bit.
        //but it allows a custom Comparator
    //    public static void main(String[] arg) {
    //        Comparator c = new Comparator(){
    //            private FileSystemView
    //                fsv = FileSystemView.getFileSystemView()
    //            private boolean ignoreLength(File f){
    //                //avoid calls to isDirectory for FileSystemRoots and the like.
    //                //may need some tweaking
    //                if( fsv.isFileSystemRoot(f) )
    //                    return true;
    //                if( f.isDirectory() )
    //                    return true;
    //                return false;
    //            public int compare(Object o1, Object o2){
    //                File f1 = (File)o1, f2 = (File)o2; //ClassCast
    //                if( ignoreLength(f1) ) return -1;
    //                if( ignoreLength(f2) ) return 1;
    //                return (int) (f1.length() - f2.length());
    //        JFileChooser jfc = createMetalFileChooser(c);
    //        jfc.showDialog(null, null);
    //        System.exit(0);
        //this is variant two. Clean. But needs a fixed
        //UI class to act, so no runtime-comparator passing
        public static void main(String[] s){
            UIManager.put("FileChooserUI", "test.CustomFileChooser$MetalChooserUIThatSortsBySize");
            JFileChooser jfc = new JFileChooser();
            jfc.showDialog(null, null);
            System.exit(0);
    }Regards,
    O. W. A. Giveaway (dec'd.)

  • Cursor Busy in JFileChooser

    I am using a JFileChooser to open directories, some of the directories can contain a lot of sub directories and it can take a while to update the display with the contents (5 seconds), but the JFileChooser doesnt show a busy cursor whilst doing this so can appear to the user that the directory is empty.
    is this a bug in java , i havent found anything in the Bug Database. ?
    Running on Windows JDK 1.5.

    It should work if "parent" is a Window.
    I do notice a problem if you navigate to an empty directory, in which case there is no
    contentsChanged event and the wait cursor doesn't go away. I will investigate if there
    is a solution for that.
    Here is a complete example.
    import java.awt.*;
    import java.beans.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    public class bug5010850 {
        public static void main(String[] args) throws Exception {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    final JFileChooser fc = new JFileChooser();
                    FileChooserUI ui = fc.getUI();
                    if (ui instanceof BasicFileChooserUI) {
                        fc.addPropertyChangeListener(new PropertyChangeListener() {
                            public void propertyChange(PropertyChangeEvent e) {
                                String s = e.getPropertyName();
                                if (s.equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
                                    setCursor(fc, Cursor.WAIT_CURSOR);
                        ListModel model = ((BasicFileChooserUI)ui).getModel();
                        model.addListDataListener(new ListDataListener() {
                            public void contentsChanged(ListDataEvent e) {
                                setCursor(fc, Cursor.DEFAULT_CURSOR);
                            public void intervalAdded(ListDataEvent e) { }
                            public void intervalRemoved(ListDataEvent e) { }
                    fc.showSaveDialog(null);
                private void setCursor(JComponent comp, int type) {
                    Window window = SwingUtilities.getWindowAncestor(comp);
                    if (window != null) {
                        Cursor cursor = Cursor.getPredefinedCursor(type);
                        System.out.println(cursor);
                        window.setCursor(cursor);
            System.exit(0);
    }

  • How to load ImagePreview in JFileChooser in another thread?

    Hello,
    I'm trying to display an image preview in JFileChooser for image files using an accessory.
    It works, but the problem is that the dialog freezes until the image is loaded.
    Is there any way to load the preview in background so you can click "Open" regardless it is fully loaded?
    This is my code, I used a new Thread in loadImage, but it still freezes:
    package OpenImage;
    import javax.swing.*;
    import java.beans.*;
    import java.awt.*;
    import java.io.File;
    public class ImagePreview extends JComponent implements PropertyChangeListener {
         ImageIcon thumbnail = null;
         File file = null;
         public ImagePreview(JFileChooser fc) {
              setPreferredSize(new Dimension(200, 200));
              fc.addPropertyChangeListener(this);
         public void loadImage() {
              if (file == null) {
                   thumbnail = null;
                   return;
              ImageIcon tmpIcon = new ImageIcon(file.getPath());
              if (tmpIcon != null) {
                   if (tmpIcon.getIconWidth() > 200) {
                        thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(
                                  200, -1, Image.SCALE_FAST));
                   } else {
                        thumbnail = tmpIcon;
         public void propertyChange(PropertyChangeEvent e) {
              boolean update = false;
              String prop = e.getPropertyName();
              if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                   file = null;
                   update = true;
              } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
                   file = (File) e.getNewValue();
                   update = true;
              if (update) {
                   thumbnail = null;
                   repaint();
                   if (isShowing()) {
                        new Thread() {
                             public void run() {
                                  loadImage();
                                  repaint();
                        }.start();
         protected void paintComponent(Graphics g) {
              if (thumbnail == null) {
                   loadImage();
              if (thumbnail != null) {
                   int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
                   int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;
                   if (y < 0) {
                        y = 0;
                   if (x < 5) {
                        x = 5;
                   thumbnail.paintIcon(this, g, x, y);
    If this is in the wrong section, please move the post.
    Any help is appreciated.

    810932 wrote:
    This is my code, I used a new Thread in loadImage, but it still freezes:Then you didn't start the thread properly. Did you use run() in stead of start() by any chance?

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

Maybe you are looking for

  • Read from text file and seperate column

    hello, I have a problem reading my text file. This text file is downloaded from weather link. All data will be changed upon the selection of user. my problem is I can read the data column by column but i cannot retrive the right column header for eac

  • Hard drive adapter

    Recently upgraded to solid state drive instead of orig Fujitsu. Now I need the adapter that allows the 2.5" drive to drop down onto the installed pins rather than be inserted horizontally.  Any idea where I can find one of these (other than on the or

  • New to this and can't open any files

    I'm real new to this InDesign program and already have a problem.  I can't open any Photoshop files, esp files, pdf files.  I can't even open InDesign files. I get a message that I am missing plug ins.  What am I **** wrong.  When the program was ins

  • Make Onlocation open source.... PLEASE!!!

    Since the engineers at adobe are clueless in regards to the possibilities of onlocation, I think they would be well served to release the source code for onlocation and make it open source.

  • AbstractAction - Dynamic Callbacks?

    I'm using AbstractAction for the first time and I'm running into a design/organization issue. I want my Actions to delegate back to the controller when the Action is triggered. So my concrete implementation of AbstractClass takes some kind of interfa