2015-07-02 42 views
0

我做了一個按鈕,你可以選擇你想要的文件,但是我只想製作第一個按鈕顯示的圖片,而第二個只顯示網頁,所以用戶不能選擇其他的,但它不會工作。當我打開filechooser時,如何選擇FileFilter應顯示的內容?

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); 
+0

一個完整的compilable類將是偉大的。 :-) – Amber

回答

0

你只需要對圖像產生的JFileChooser的文件

JFileChooser openFile = new JFileChooser(); 

      openFile.setFileFilter(new FileNameExtensionFilter("Image files (*.GIF,*.PNG,*.JPG, *.JPEG)", "GIF","PNG","JPG", "JPEG")); 

      int result = openFile.showOpenDialog(null); 

後和網頁

openFile.setFileFilter(new FileNameExtensionFilter(" HTMLDocument (*.HTML)", "HTML")); 

好運來加入這行!

0

那樣做:

String[] EXTENSION=new String[]{"jpg", "png", "etc"}; 
FileNameExtensionFilter filter=new FileNameExtensionFilter("Images",EXTENSION); 
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

相關問題