JFileChooser repaint

Hello,
I am opening a JFileChooser from a menu FILE > OPEN. When I click OPEN, I want to change a status message being displayed, then open JFileChooser. Somehow the repaint doesn't happen: when JFileChooser finally opens, if I drag it to one side and look at the launching window underneath, yep, the message is displayed.
Next, right after I select a file in JFileChooser, I first want to repaint the window underneath properly before I do something intensive with the file -- once again the refresh isn't happening correctly, the window greys out and is repainted only after the long task is done.
Have tried super.repaint(), repaint(), repaint() in a try/catch, all with the same result.
Have stripped down my code to demo my problem, will much appreciate guidance. Thanks in advance!
//ChangeMessage.java
//simplified code to demonstrate repaint problem right before
//opening JFileChooser and right after selecting a file
import java.io.File;
import java.util.Locale;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
public class ChangeMessage extends JFrame implements ActionListener
private JMenuItem openItem;
private JMenuItem exitItem;
private JMenuItem aboutItem;
private JTextField txtStatus;
public String filename;
public ChangeMessage()
          setTitle("ChangeMessage");
          setSize(430,145);
          setLocation(50,50);
          setResizable(false);
          Container contentPane = getContentPane();
          //Set up the window controls:
          GridBagLayout gbl = new GridBagLayout();
          contentPane.setLayout(gbl);
          //menu starts:
          JMenuBar mbar = new JMenuBar();
          JMenu m = new JMenu("File");
          openItem = new JMenuItem("Open");
          openItem.addActionListener(this);
          m.add(openItem);
          exitItem = new JMenuItem("Exit");
          exitItem.addActionListener(this);
          m.add(exitItem);
          mbar.add(m);
          JMenu n = new JMenu("Help");
          aboutItem = new JMenuItem("About");
          aboutItem.addActionListener(this);
          n.add(aboutItem);
          mbar.add(n);
          //menu ends
          GridBagConstraints gbc = new GridBagConstraints();
          gbc.fill = GridBagConstraints.BOTH;
          gbc.weightx = 200;
          gbc.weighty = 50;
          add(mbar,gbc,0,0,7,1);
          gbc.weightx = 20;
          txtStatus = new JTextField("Select a text file by doing menu FILE > OPEN",300);
          txtStatus.setEditable(false);
          txtStatus.setBorder(BorderFactory.createBevelBorder(1));
          txtStatus.setHorizontalAlignment(JTextField.CENTER);
          txtStatus.setForeground(Color.blue);
          gbc.weightx = 0;
          gbc.weighty = 15;
          add(txtStatus,gbc,0,1,7,1);
          gbc.weightx = 50;
          gbc.anchor = GridBagConstraints.EAST;
public void actionPerformed(ActionEvent evt)
          Object source = evt.getSource();
     if (source == openItem)
               //On my system, you click and wait for the File Chooser, so
               //want to show an hourglass:
               super.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
               //PROBLEM: WANT TO SEE THE FOLLOWING WHILE WAITING:
               txtStatus.setText("Opening file chooser window...");
               repaint();
               JFileChooser chooser = new JFileChooser();
               chooser.setCurrentDirectory(new File("."));
               chooser.setFileFilter(new FileFilter()
                    public boolean accept(File f)
                         return f.getName().toLowerCase().endsWith(".txt") || f.isDirectory();
                    public String getDescription()
                         return "Plain text file (.TXT)";
     int r = chooser.showOpenDialog(this);
               super.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
     if (r == JFileChooser.APPROVE_OPTION)
               filename = chooser.getSelectedFile().getPath();
               repaint();
               //PROBLEM: DOING SOMETHING INTENSIVE HERE "BLANKS OUT" window
               //do something with the file
     else if (source == aboutItem)
     else if (source == exitItem)
               System.exit(0);
     public void add(Component c,GridBagConstraints gbc,int x,int y,int w,int h)
          gbc.gridx = x;
          gbc.gridy = y;
          gbc.gridwidth = w;
          gbc.gridheight = h;
          getContentPane().add(c,gbc);
public static void main(String[] args)
          JFrame.setDefaultLookAndFeelDecorated(true);
          Frame f = new ChangeMessage();
          f.show();

Hello,
Just wanted to mention that I resolved this, using SwingWorker. So the answer is yes, I needed to launch another thread.
The complete source code is available to anyone interested at:
http://www.quadmore.com/babytalk/index.html
Cheers,
Bert Szoghy

Similar Messages

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

  • 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 and the filename

    Hi All,
    I'm going for 11 new things learned today about Java!
    I'm using JFileChooser to prompt for a file, and I need to capture the filename and see if it's inside the file.
    I'm getting a "found int, expected boolean" compile error. Can comeone enlighten?
    Thanks!
    MVP
    String strFileName;
    JFileChooser jfc = new JFileChooser();
    strFileName = jfc.getSelectedFile().getName();  // tried both these
    strFileName = jfc.getName(); // lines
    currentLine = strInFileArray;
    if(currentLine.indexOf(strFileName)) //compile error on this line

    I didn't say it didn't compile, it does compile.
    And I know it doesn't do anything because I display
    currentLine before and after the change is attempted.
    And I did read up on the method - how do you think I
    found it in the first place?If you did, then what does it say after the word "Returns" in the method description? And where else could you have found the method? Some IDEs will spit out a list of possible methods that can be called from an option. One of the reaosns why I suggest new comers shouldn't use IDEs to start (forces them to learn about the API which is the best possible thing for someone in your (ie newbie, nothing personal) possition to do).
    >
    Now, if statements like
    i++
    setBackground(Color.WHITE)
    setFont(myfont)
    getContentPane().setLayout()
    repaint()
    and others (iow, no '=' for assignment)
    all change objects or attributes of objects, it seems
    a logical assumption to me that
    currentLine.replaceAll(strFileName,NEW_FILE_NAME);
    will change the object 'currentLine'.So you assume that all methods work the sae way, and forget the docs? The first sentance of the second paragraph in the String API says:
    "Strings are constant; their values cannot be changed after they are created. "
    So you see, the answer to your question, and the why it is the way it is, are both in the API.
    >
    Finally, (not for you jverd, you are polite), to be
    called names by supposedly mature posters on this
    forum - which exists specifically for beginner-level
    questions like mine - is just amazing. Excuse me for
    thinking I might find help and assistance instead of
    abuse.A double standard, yes? I have to be mature, but not you? You whine alot. You can ask questions without whining, others do it all the time (you didn't whine in the first question in this thread, and I tried to answer (well, tried to get you to answer yourself, which I believe is more beneficial)). Once you started your whining again, I became immature also. No apologies here.
    And even if the assinine (which it was intentionally) it still had some help (by pointing to the API). You saw the API before (which is good) but I did not know that, and your questions seemed to indicate otherwise.
    >
    TheReallyDisappointedMVPBuck up. Nothing personal. Just ask questions differently, that's all.

  • Problem in OPENING file saved as .bmp(JFilechooser)  in PAINTBRUSH / WIN98

    hello
    Using the JFileChooser I saved the contents of a canvas as " .bmp" file
    now when I try to open this ".bmp" file in the paintbbrush application in windows, I am not able to open.,......
    can anyone pls explain me why ?? how ???
    also the vice- versa is not happening....
    a filed saved in ".bmp" format by the paintbrush is not opened in the java using the JFilechooser ???
    I tried to search the forum but not able to find the solution.....
    am still hunting......
    Kind Rgds
    ASHWIN

    post some code .........the code is as follows.............
    for saving.......
    JFileChooser chooser = new JFileChooser();
    int option = chooser.showSaveDialog(this);
    if( option == JFileChooser.APPROVE_OPTION) {
    path = chooser.getSelectedFile().getAbsolutePath();
    saveFile(path);
    public void saveFile(String path){
    try{
    FileOutputStream ostream = new FileOutputStream(path);
         ObjectOutputStream p = new ObjectOutputStream(ostream);
    p.writeObject(points);
    p.writeObject(drawType);
    catch( Exception e){
    System.err.println(e);
    and for opening.........
    JFileChooser chooser = new JFileChooser();
    int option = chooser.showOpenDialog(this);
    if( option == JFileChooser.APPROVE_OPTION) {
    path=chooser.getSelectedFile().getAbsolutePath();
    openFile(path);
    public void openFile(String path){
    try{
    FileInputStream fstream = new FileInputStream(path);
    ObjectInputStream iii = new ObjectInputStream(fstream);
    points = (Vector)iii.readObject();
    repaint();
    catch(Exception e){
    System.out.println("file not found" + e);
    FOR camickr
    please tell me if you know
    HOW TO SAVE A FILE IN " .bmp" format.... so that it could be opened in
    paintbrush application in WIN 98...
    kind rgds
    ASHWIN...

  • Paint and repaint

    Hi I've got a simple question how to you repaint somthing that's not a Component?
    When I get the string I want to paint it on screen but I need to repaint first, how?
    import java.awt.*;
    import java.io.*;
    public class myList
    public String[] name = new String[1000];
    int Counter = 0;
    public void getFile(String str)
      name[Counter] = str;
      Counter++;
      //Want repaint here
    public void paint(Graphics g)
      name[0] = "Hej";
      for(int i = 0;i < name.length; i++)
       if(name[i] != null)
       g.drawString(name,10,50 + 20*i);

    I do not belive this is swing related since I want to get the method of repainting the AWT version of paint.
    Once again I'll show some code (stripped down for you)
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import java.net.*;
    public class myPanel
    JPanel panel;
    JButton openButton;
    myList ml = new myList();
    public myPanel()
      panel = new JPanel()
       public void paintComponent(Graphics g)
        super.paintComponent(g);
        ml.paint(g);
      openButton.addActionListener(new ActionListener()
       public void actionPerformed(ActionEvent e)
         //the file variable I get from a JFileChooser
         //This is where a real application would open the file.
         ml.getFile(file.getName());
         panel.repaint();
         //I maybe want to repaint ml.paint() here
      panel.add(stopButton);
      panel.add(openButton);
      panel.add(saveButton);
    import java.awt.*;
    import java.io.*;
    public class myList
    public String[] name = new String[1000];
    int Counter = 0;
    public void getFile(String str)
      name[Counter] = str;
      Counter++;
      //Want a repaint here
    public void paint(Graphics g)
      for(int i = 0;i < name.length; i++)
       if(name[i] != null)
       g.drawString(name,10,50 + 20*i);
    //Or here

  • Altering a Panel during runtime, repaint etc not working!

    Hello all,
    I have had a look around this forum for similar problems and all suggestions seem to say use repaint(), revalidate() or validate() to get a JPanel to update, however none of these seem to work for me.
    Basically I have a program with multiple panels, one of which is affectedd by JFileChooser, when a new directory is selected the panel alters to show certain files in that directory...all the data alters correctly but the panel will not refresh.
    void changeDirectory(String dir){
              currentDirectory = formatDir(dir);
              thumbPanel = new JScrollPane(new thumbnailWindow());
              add(thumbPanel, BorderLayout.CENTER);
              thumbPanel.validate();
              setVisible(true);
         }this is a small snippet of my code and the bit that is giving me the problem,
    thumbPanel already exists and is shown in my main program, when the directory is changed the data is altered, so i then want thumbpanel to refrence a new thumbpanel and over write the previous one.
    I have already tried to remove the panel first then re add, aswell as repaint, validate, and revalidate. I know this is going to be something fundamental but I don't have a clue what to do now.
    All help, comments and criticism is welcomed,
    Regards,
    Chris.

    /* your current code */
    void changeDirectory(String dir){
      currentDirectory = formatDir(dir);
      thumbPanel = new JScrollPane(new thumbnailWindow());
      add(thumbPanel, BorderLayout.CENTER);
      thumbPanel.validate();
      setVisible(true);
    /* correct code */
    void changeDirectory(String dir){
      currentDirectory = formatDir(dir);
      thumbPanel.setViewportView(new thumbnailWindow());
    }

  • Load, crop and saving jpg and gif images with JFileChooser

    Hello!
    I wonder is there someone out there who can help me with a applic that load, (crop) and saving images using JFileChooser with a simple GUI as possible. I'm new to programming and i hope someone can show me.
    Tor

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
    public class ChopShop extends JPanel {
        JFileChooser fileChooser;
        BufferedImage image;
        Rectangle clip = new Rectangle(50,50,150,150);
        boolean showClip = true;
        public ChopShop() {
            fileChooser = new JFileChooser(".");
            fileChooser.setFileFilter(new ImageFilter());
        public void setClip(int x, int y) {
            clip.setLocation(x, y);
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(image != null) {
                int x = (getWidth() - image.getWidth())/2;
                int y = (getHeight() - image.getHeight())/2;
                g2.drawImage(image, x, y, this);
            if(showClip) {
                g2.setPaint(Color.red);
                g2.draw(clip);
        public Dimension getPreferredSize() {
            int width = 400;
            int height = 400;
            int margin = 20;
            if(image != null) {
                width = image.getWidth() + 2*margin;
                height = image.getHeight() + 2*margin;
            return new Dimension(width, height);
        private void showOpenDialog() {
            if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    image = ImageIO.read(file);
                } catch(IOException e) {
                    System.out.println("Read error for " + file.getPath() +
                                       ": " + e.getMessage());
                    image = null;
                revalidate();
                repaint();
        private void showSaveDialog() {
            if(image == null || !showClip)
                return;
            if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                String ext = ((ImageFilter)fileChooser.getFileFilter()).getExtension(file);
                // Make sure we have an ImageWriter for this extension.
                if(!canWriteTo(ext)) {
                    System.out.println("Cannot write image to " + ext + " file.");
                    String[] formatNames = ImageIO.getWriterFormatNames();
                    System.out.println("Supported extensions are:");
                    for(int j = 0; j < formatNames.length; j++)
                        System.out.println(formatNames[j]);
                    return;
                // If file exists, warn user, confirm overwrite.
                if(file.exists()) {
                    String message = "<html>" + file.getPath() + " already exists" +
                                     "<br>Do you want to replace it?";
                    int n = JOptionPane.showConfirmDialog(this, message, "Confirm",
                                                          JOptionPane.YES_NO_OPTION);
                    if(n != JOptionPane.YES_OPTION)
                        return;
                // Get the clipped image, if available. This is a subImage
                // of image -> they share the same data. Handle with care.
                BufferedImage clipped = getClippedImage();
                if(clipped == null)
                    return;
                // Copy the clipped image for safety.
                BufferedImage cropped = copy(clipped);
                boolean success = false;
                // Write cropped to the user-selected file.
                try {
                    success = ImageIO.write(cropped, ext, file);
                } catch(IOException e) {
                    System.out.println("Write error for " + file.getPath() +
                                       ": " + e.getMessage());
                System.out.println("writing image to " + file.getPath() +
                                   " was" + (success ? "" : " not") + " successful");
        private boolean canWriteTo(String ext) {
            // Support for writing gif format is new in j2se 1.6
            String[] formatNames = ImageIO.getWriterFormatNames();
            //System.out.printf("writer formats = %s%n",
            //                   java.util.Arrays.toString(formatNames));
            for(int j = 0; j < formatNames.length; j++) {
                if(formatNames[j].equalsIgnoreCase(ext))
                    return true;
            return false;
        private BufferedImage getClippedImage() {
            int w = getWidth();
            int h = getHeight();
            int iw = image.getWidth();
            int ih = image.getHeight();
            // Find origin of centered image.
            int ix = (w - iw)/2;
            int iy = (h - ih)/2;
            // Find clip location relative to image origin.
            int x = clip.x - ix;
            int y = clip.y - iy;
            // clip must be within image bounds to continue.
            if(x < 0 || x + clip.width  > iw || y < 0 || y + clip.height > ih) {
                System.out.println("clip is outside image boundries");
                return null;
            BufferedImage subImage = null;
            try {
                subImage = image.getSubimage(x, y, clip.width, clip.height);
            } catch(RasterFormatException e) {
                System.out.println("RFE: " + e.getMessage());
            // Caution: subImage is not independent from image. Changes
            // to one will affect the other. Copying is recommended.
            return subImage;
        private BufferedImage copy(BufferedImage src) {
            int w = src.getWidth();
            int h = src.getHeight();
            BufferedImage dest = new BufferedImage(w, h, src.getType());
            Graphics2D g2 = dest.createGraphics();
            g2.drawImage(src, 0, 0, this);
            g2.dispose();
            return dest;
        private JPanel getControls() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(getCropPanel(), gbc);
            panel.add(getImagePanel(), gbc);
            return panel;
        private JPanel getCropPanel() {
            JToggleButton toggle = new JToggleButton("clip", showClip);
            toggle.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    showClip = ((AbstractButton)e.getSource()).isSelected();
                    repaint();
            SpinnerNumberModel widthModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner widthSpinner = new JSpinner(widthModel);
            SpinnerNumberModel heightModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner heightSpinner = new JSpinner(heightModel);
            ChangeListener cl = new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    JSpinner spinner = (JSpinner)e.getSource();
                    int value = ((Number)spinner.getValue()).intValue();
                    if(spinner == widthSpinner)
                        clip.width = value;
                    if(spinner == heightSpinner)
                        clip.height = value;
                    repaint();
            widthSpinner.addChangeListener(cl);
            heightSpinner.addChangeListener(cl);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            panel.add(toggle, gbc);
            addComponents(new JLabel("width"),  widthSpinner,  panel, gbc);
            addComponents(new JLabel("height"), heightSpinner, panel, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc) {
            gbc.anchor = GridBagConstraints.EAST;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(c2, gbc);
        private JPanel getImagePanel() {
            final JButton open = new JButton("open");
            final JButton save = new JButton("save");
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JButton button = (JButton)e.getSource();
                    if(button == open)
                        showOpenDialog();
                    if(button == save)
                        showSaveDialog();
            open.addActionListener(al);
            save.addActionListener(al);
            JPanel panel = new JPanel();
            panel.add(open);
            panel.add(save);
            return panel;
        public static void main(String[] args) {
            ChopShop chopShop = new ChopShop();
            ClipMover mover = new ClipMover(chopShop);
            chopShop.addMouseListener(mover);
            chopShop.addMouseMotionListener(mover);
            JFrame f = new JFrame("click inside rectangle to drag");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(chopShop));
            f.getContentPane().add(chopShop.getControls(), "Last");
            f.pack();
            f.setLocation(200,100);
            f.setVisible(true);
    class ImageFilter extends FileFilter {
        static String GIF = "gif";
        static String JPG = "jpg";
        static String PNG = "png";
        // bmp okay in j2se 1.5+
        public boolean accept(File file) {
            if(file.isDirectory())
                return true;
            String ext = getExtension(file).toLowerCase();
            if(ext.equals(GIF) || ext.equals(JPG) || ext.equals(PNG))
                return true;
            return false;
        public String getDescription() {
            return "gif, jpg, png images";
        public String getExtension(File file) {
            String s = file.getPath();
            int dot = s.lastIndexOf(".");
            return (dot != -1) ? s.substring(dot+1) : "";
    class ClipMover extends MouseInputAdapter {
        ChopShop component;
        Point offset = new Point();
        boolean dragging = false;
        public ClipMover(ChopShop cs) {
            component = cs;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(component.clip.contains(p)) {
                offset.x = p.x - component.clip.x;
                offset.y = p.y - component.clip.y;
                dragging = true;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        public void mouseDragged(MouseEvent e) {
            if(dragging) {
                int x = e.getX() - offset.x;
                int y = e.getY() - offset.y;
                component.setClip(x, y);
    }

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

  • NullPointerException in JFileChooser

    Hello,
    I have a method which shows a JFileChooser to select a save name. After click on the dialog's OK button, sometimes it throws NullPointerException.
    I have checked the thread, and everything runs in EDT, so this should not be the problem.
    The calling code is
    public File getSelectedFile() {
    chooser = new JFileChooser(prefs.get(Configuration.KEY_LAST_SAVED_DIR, null));
    chooser.setSelectedFile(new File(defaultFileName));
    for(ExtensionFileFilter f : fileTypes){
    chooser.addChoosableFileFilter(f);
    if (defaultFilter == null) {
    chooser.setFileFilter(chooser.getAcceptAllFileFilter());
    } else {
    chooser.setFileFilter(defaultFilter);
    // That's where it happens
    int returnVal = chooser.showSaveDialog(parentComponent);
    prefs.put(Configuration.KEY_LAST_SAVED_DIR,chooser.getCurrentDirectory().getAbsolutePath());
    return chooser.getSelectedFile();
    Can you help me spot where the problem is?
    The stack trace is below.
    Thanks for any suggestions.
    Karl
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.JComponent.repaint(JComponent.java:4728)
    at sun.swing.FilePane$2.repaintListSelection(FilePane.java:114)
    at sun.swing.FilePane$2.repaintSelection(FilePane.java:104)
    at sun.swing.FilePane$2.focusLost(FilePane.java:99)
    at java.awt.AWTEventMulticaster.focusLost(AWTEventMulticaster.java:213)
    at java.awt.Component.processFocusEvent(Component.java:5930)
    at java.awt.Component.processEvent(Component.java:5794)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:878)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:551)
    at java.awt.Component.dispatchEventImpl(Component.java:4282)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:177)
    at java.awt.Dialog$1.run(Dialog.java:1039)
    at java.awt.Dialog$3.run(Dialog.java:1091)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.Dialog.show(Dialog.java:1089)
    at javax.swing.JFileChooser.showDialog(JFileChooser.java:723)
    at javax.swing.JFileChooser.showSaveDialog(JFileChooser.java:651)
    at io.FileSaver.getSelectedFile(FileSaver.java:141)
    at io.SaverManager.<init>(SaverManager.java:96)
    at io.SaverHolder$SaveSelector.actionPerformed(SaverHolder.java:153)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6038)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
    at java.awt.Component.processEvent(Component.java:5803)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    at java.awt.Container.dispatchEventImpl(Container.java:2102)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

    My first answer was wrong because the constructor which can handle a null input is the one taking a File. But from the prefs I get a String... So the I need to check first if the string is null and make a File out of it...
    About your idea to use the debugger, I can see where the problem happens (see also the stack trace above). It's when the dialog is showing (Dialog.show has been called) and then, after pressing OK, the Component gets repainted
    java.lang.NullPointerException
    at javax.swing.JComponent.repaint(JComponent.java:4728)
    Unfortunately the problem is only showing once in a while, so it's hard to test solutions...
    Thanks anyway
    Karl

  • JFileChooser - can focus be set to textfield?

    when displaying a JFileChooser, focus defaults to the open button.
    is there anyway to change this behavior?
    even a hack, like someway to use the mnemonic for the text field before
    the FileChooser is displayed?
    thanks,
    Greg

    Thanks,
    I didn't know about the getComponent method in container.
    I found the direct subcomponents in JFileChooser are JPanels.
    I went down a second level and found still more Jpanels, which had JLabels but
    no JTextField.
    I tried requesting focus to the JLabel, but this did not work.
    I tried repainting the component, and repainting JFileChooser, still didnt change focus
    from the open button.
    But thanks for getting back to me and getting me in the right direction.
    Try manually finding the JTextField and then
    requesting focus. Assuming that the text field is in
    fact a JTextField, and that it's a direct child of the
    JFileChooser (dig deeper if not), the following should
    work:
    import java.awt.Component;
    import javax.swing.JFileChooser;
    import javax.swing.JTextField;
    JFileChooser myJFileChooser = new JFileChooser();
    Component nextSubComponent;
    for (int i = 0; i <
    i < myJFileChooser.getComponentCount(); i++)
    nextSubComponent =
    ent = myJFileChooser.getComponent(i);
    if ( nextSubComponent instanceof JTextField )
    ((JTextField)nextSubComponent).requestFocus();

  • Missing pieces of components (JFileChooser, JButtons, etc) help?

    The normal window in the GUI i'm working on, works fine. When i bring up a new NetFrame (e.g. preferences) the components aren't drawn completely. None of the 3 buttons show up, a few check boxes in a tabbed pane show up (not all of them), etc. When i click where a button should be, it appears. When i switch to the other tab in the pane, its contents appear (except for a small missing bottom right corner of the border for a jtextarea), and when i switch back to the first tab, all of its contents appear. When i resize the panel, everything shows up.
    I've tried calling validate, revalidate, validateTree, repaint, show, pack, none of them do anything (pack rearranges things, but nothing new appears).
    I'm completely out of ideas!
    A previous version of the program works fine, so it is something wrong with my code (i.e. not my computer / packages etc).
    The thing that really stumps me, is that a JFileChooser appears incomplete -- only showing the file browser section, and the okay button (missing cancel button, and borders etc).
    I'm sorry i don't have any sample code to show, there too much to put it all, and i have no idea where the problem is.
    I'd appreciate any help or direction you have. THANKS!

    possibly related
    [http://forums.sun.com/thread.jspa?threadID=780103]

  • GUI Update for JDialog/JFileChooser

    Hello, Howdy, Greets, Yo and anything else I missed!
    Lets see if I can explain this well...
    I have a JDialog open in the background. One of the choices on the JDialog is to open the JFileChooser. Whenever I open the JFileChooser the JFileChooser opens in front of the JDialog (like it's supposed to). Therefore there is some overlap of the JFileChooser on top of the JDialog.
    When exiting the JFileChooser (a directory is selected), The JFileChooser GUI partially closes. It closes everywhere but where it overlaps the JDialog. So, for a few seconds it has the GUI of the JFileChooser ONLY where it overlaps the JDialog on the screen. Then after some processing (doing what it does with the JFileChooser data), it finishes removing the JFileChooser GUI that overlaps the JDialog.
    I want the JFileChooser to completely disappear at the same time. I've tried every variation I can think of, to no avail:
    dialog.repaint();
    dialog.validateTree();
    dialog.validate();
    jfc.hide();
    jfc.updateUI();
    jfc.revalidate();
    jfc.repaint();
    Here's an example:
    int choice = jfc.showDialog(new JFrame(), "Select Directory");
    // Tried everything here to hide/remove the jfc GUI
    if (choice == JFileChooser.APPROVE_OPTION )
      // do what it does with the selected directory
    }This happens on every look and feel, so that's probably not the problem. Any ideas?

    Thanks for the advice on threads. I got it working by doing the following...
          int state = jfc.showDialog(new JFrame(), "Select Directory");
          if (state == JFileChooser.APPROVE_OPTION )
            defaultDir = jfc.getSelectedFile();
            Thread myThread=new Thread()
              public void run()
                // Do my other stuff here
            myThread.start();       
          }

  • JFileChooser voodoo (what in the world is going on

    Hi all,
    I have the following sequence in my code (notice the 3 printouts):
    protected void paint() // override for a canvas method
        doFileStuff();
        System.out.println("after" + Thread.currentThread().getId());    // <-- print
    private DNA doFileStuff()
        try
          System.out.println("filing:" + Thread.currentThread().getId());    // <-- print
          JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
          chooser.setAcceptAllFileFilterUsed(false);
          chooser.addChoosableFileFilter(new FileFilter()
              public boolean accept(File pathname)
                return pathname.isDirectory() ||
                  pathname.getName().substring(pathname.getName().lastIndexOf('.') + 1).equalsIgnoreCase("dna");
              public String getDescription()
                return "DNA files (*.dna)";
          int result = chooser.showOpenDialog(null);
          System.out.println("unfiling:" + Thread.currentThread().getId());    // <-- print
          if (result == JFileChooser.ERROR_OPTION)
            throw new IOException();
          if (result == JFileChooser.CANCEL_OPTION)
            return null;
          File file = chooser.getSelectedFile();
          ObjectInputStream inputstream = new ObjectInputStream(new FileInputStream(file.getAbsolutePath()));
          int[] nucleotides = (int[])inputstream.readObject();
          inputstream.close();
          return new DNA(nucleotides);
        catch (Exception e)
          // TOMER: add error message here
          return null;
    }This is run in the context of the AWT-EventQueue-0 thread with id 14.
    When i run this i get the file dialog to show which is great.
    However when i don't click on anything, don't choose a file and just let it stand there, the printouts i am seeing in the output are:
    filing: 14
    after: 14
    after: 14
    after: 14
    after: 14
    after: 14not getting the middle "unfiling" print which makes sense since the call "showOpenDialog" should be blocking (as far as i know).
    but i'd also expect to not see the "after" print.
    what is going on here?
    I am assuming repaint is being called again and again but since the dialog is opened from the eventqueue thread those repaint events should be ignored until the file is chosen no?
    It is either something very voodoo-ish or i am missing something very basic (i assume the latter :))
    Thanks for any help in advance

    I know it's a shot in the dark without a proper SSCCE, but hey I do what I want with my pause time!
    So, OP:
    - first, it is a very bad idea to spawn a dialog boxfrom a paint(Graphics) method (your paint method has no argument, but as you say it's an override I assume you forgot it).
    Paint(Graphics) is designed to, well, paint the component on screen, according to its current state.
    A paint(Graphics) method is also designed to be called on the event-dispatch-thread (EDT), which is dedicated to handle graphical events including "paint events", so it must execute quickly. In particular, business logic, file reading, and worst of all, waiting for user input, is not relevant in a paint() method.
    I am assuming repaint is being called again and again but since the dialog is opened from the eventqueue thread those repaint events should be ignored until the file is chosen no?You don't know if they are repaint(), or paintImmediately() calls. You could set a breakpoint in a debugger, or log the stack trace, to know where these paint(...) calls come from.
    I don't know the details, but opening a dialog (at least a modal one) from the EDT somehow suspends the "regular" EDT (the showOpenDialog() is a blocking call), and spawns a dedicated EDT (after all, the dialog itself needs to handle user events to detect press on OK/close/cancel). I don't know which is the extent (in terms of components covered) of the spawned EDT.
    I ackowledge it's surprising to see the (seemingly) same thread log these traces, as per this assumption some of the logs at least should be from another thread.
    But as you show only an extract of code, and apparently have modified the code during your experiments, I can't put too much faith into the code and log you posted. You'll probably have to provide this damn SSCCE to get more help.

  • 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

  • Parent / Child Groups in Portal with LDAP

    Heya, we are using EP 7 on SP 10 (NW 7), for User Authentication we use the UME with a configured (writable) LDAP Server as backend with a flat hierarchie. We have a Federated Portal Landscape with 3 Portals connected to one "main" portal and using R

  • !!!Help!!! Cells have extra bottom space

    My site has a header. This header is a table formed by 1 row and 2 cells. One of the cells has only one image, but the other has a nested table with two other cells, having, each one, one image. Anyway, this is what my header is looking like: See thi

  • /usr/local/bin

    Hello everyone, Whenever i am installing any s/w from source by compiling,its executable is getting stored in /usr/local/bin.Now im unable to use the s/w by just typing its executable name in the terminal,its giving me an error as "command not found"

  • Why isn't my app store on my mac working?

    Every time I try and go into my app store on my mac to update my apps, it sits there loading before a box pops up and say "App store cannot verify a secure connection with the App store. Would you like to connect anyway?" I press continue and it just

  • Which SDK?

    Hi,I need to run a program which has the listed import statements.My question is,which Java SDK I need to install in order to run the program to see the output..Thanks import java.awt.*; import java.applet.Applet; import java.io.*; import java.net.*;