当我打开filechooser时,如何选择FileFilter应该显示的内容?

时间:2015-07-02 13:46:00

标签: java eclipse jfilechooser

我创建了一个按钮,您可以在其中选择所需的文件,但我只想制作第一个按钮显示的图像,而只显示第二个按钮中的网页,因此用户不能选择其他网页但不会工作。

    JButton btnImage = new JButton("Parcourir");
    btnImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser openFile = new JFileChooser();
            int result = openFile.showOpenDialog(null);
            String path= ""; 
            String source ; 
            if (result == JFileChooser.APPROVE_OPTION) {
                openFile.addChoosableFileFilter(new  FileNameExtensionFilter("Image Files", "png","GIF", "jpg"));
                File selectedFile = openFile.getSelectedFile();

                textField_1.setText(selectedFile.getName());  
            path = selectedFile.getName();
            source = "<li><img src=" +path+ "id='nnm' style='width:100%;height:100%;'></li>";   
            }else {
                JOptionPane.showMessageDialog(null, "You have to choose a file ");
         }
        }
    });
    btnImage.setVisible(false);
    btnImage.setBounds(236, 223, 89, 23);
    frame.getContentPane().add(btnImage);

        btnPageWeb.addActionListener(new ActionListener() {
        public void  actionPerformed(ActionEvent arg0) {
        JFileChooser openFile = new JFileChooser();
        int result = openFile.showOpenDialog(null);
        String path; 
        String source ; 
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = openFile.getSelectedFile();

            textField_1.setText(selectedFile.getName());  
        path = selectedFile.getName();
        source = "<li><iframe src="+path+"frameborder='0' id='nnm' style= 'width:100%;height:100%;' ></iframe></li>";
        }else {
            JOptionPane.showMessageDialog(null, "You have to choose a file ");
        }
        }

    });

    btnPageWeb.setVisible(false);
    btnPageWeb.setBounds(246, 250, 89, 23);
    frame.getContentPane().add(btnPageWeb);

3 个答案:

答案 0 :(得分:0)

这样做:

String[] EXTENSION=new String[]{"jpg", "png", "etc"};
FileNameExtensionFilter filter=new FileNameExtensionFilter("Images",EXTENSION);

答案 1 :(得分:0)

您需要在显示对话框之前设置FileFilter。像这样:

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) 
{
   // your code here
}

这是来自JFileChooser文档here

答案 2 :(得分:0)

您只需在为图像文件

创建JFileChooser后添加此行
openFile.setFileFilter(new FileNameExtensionFilter(" HTMLDocument (*.HTML)",  "HTML"));

和WEB页面

{{1}}
祝你好运!