我想限制用户可以使用JFileChooser选择的图像尺寸

时间:2012-03-19 16:07:12

标签: java swing jfilechooser

我有一个JFileChooser,可以让用户自己选择一个图像。我想将他们可以选择的图像限制为具有方形尺寸的图像,例如 -

宽度和高度均为50

宽度和高度都是75等......

因此,当他们选择带有JFileChooser的图像并单击“打开”时,我需要验证图像大小,如果它没有方形尺寸,我需要向用户显示一个对话框,通知他们“图像必须具有相同的宽度和高度“。

我只是在学习挥杆,所以我不知道该怎么做。关于如何做到这一点的任何想法?有没有办法挂钩“打开”按钮的事件处理程序?

2 个答案:

答案 0 :(得分:4)

您可以隐藏所有未通过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
    }
}

答案 1 :(得分:0)

我试过覆盖

public void approveSelection () 

从JFileChooser派生自己的类,乍一看,它似乎有效。

调用该方法,我可以对所选文件进行测试,如果失败,则调用showOpenDialog (ref);

但是......

它工作正常,当我调用一个合法的文件时,它会打开一个新的对话框,如果没有,但在那之后,对话框将不会再正常关闭,如果被窗口的X强制,我得到一个StackTrace打印。所以我猜对话框的状态在这里是关键的 - 如果递归调用'showOpenDialog'它就不起作用。

以下是我测试过的变体之一:

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 ();
    }
}

为了简化测试,我只测试了文件名以包含“e”。

所以我建议使用Boris的方法,并在完成对话后测试你的文件。如果失败,立即重新打开一个新的。