csss
csss

Reputation: 1997

I want to restrict the dimensions of images users can select with a JFileChooser

I have a JFileChooser that lets users choose an image for themselves. I want to limit the images they can choose to ones with square dimensions, for example -

width and height both 50

width and height both 75, etc...

So when they select an image with the JFileChooser and click 'Open' I need to validate the image size and if it doesn't have square dimensions I need to present the user with a dialog informing them "The image must have the same width and height".

I'm just learning swing so I don't know how to do this. Any ideas on how to do this? Is there a way of hooking the "Open" button's event handler?

Upvotes: 0

Views: 586

Answers (2)

user unknown
user unknown

Reputation: 36229

I tried overwriting

public void approveSelection () 

by deriving a own class from JFileChooser, and at first glance, it seemed to work.

The method is called, I can make a test on the selected file, and, if it fails, recall showOpenDialog (ref);.

But ...

It works fine, when I call a legitimate file, and it opens a new dialog, if not, but after that, the dialog won't close again normally, and if forced by the X of the window, I get a StackTrace printed. So I guess the state of the dialog is the critical thing here - it doesn't work if 'showOpenDialog' is called recursively.

Here is one of the variants I tested:

class ProportionalImageChooser extends JFileChooser
{
    private Component ref;
    
    public ProportionalImageChooser (File f)
    {
        super (f);
    }
    
    public int showOpenDialog (Component parent) 
    {
        ref = parent;
        return super.showOpenDialog (parent);
    }

    public void approveSelection () {
        System.out.println ("approving selection!");
        String fname = getSelectedFile ().getName (); 
        if (fname.matches (".*e.*")) {
            cancelSelection ();
            System.out.println ("Dialog: size doesn't match");
            showOpenDialog (ref);
        }
        else super.approveSelection ();
    }
}

To keep the test simple, I only tested the filename to include an 'e' or not.

So I suggest, use Boris' approach, and test your file after finishing the dialog. If it fails, immediately reopen a new one.

Upvotes: 0

Boris Pavlović
Boris Pavlović

Reputation: 64632

You can hide all images that do not confirm to the rules with an implementation of a FileFilter:

JFileChooser fileChooser = new JFileChooser(new File(filename));
fileChooser.addChoosableFileFilter(new MyFilter());

// Open file dialog.
fileChooser.showOpenDialog(frame);
openFile(fileChooser.getSelectedFile());

class MyFilter extends javax.swing.filechooser.FileFilter {
    public boolean accept(File file) {
        // load the image
        // check if it satisfies the criteria
        // return boolean result
    }
}

Upvotes: 4

Related Questions