2015-01-12 3 views
1

Я работаю над PDF-файловым файлом, и благодаря помощи переполнения стека я добился большого прогресса, у меня возникла еще одна проблема с моим кодом. Я создал все элементы, необходимые для создания этой функции проводника файлов, но эти два класса не сообщают должным образом. вот мой код package pdfView;PDF-файл File explorer

import java.io.*; 
import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 
import javax.swing.filechooser.*; 

public class FileChooser2 extends JPanel implements ActionListener { 

    static private final String newline = "\n"; 
     JButton openButton, saveButton; 
     JTextArea log; 
     JFileChooser fc; 

     public FileChooser2() { 
      super(new BorderLayout()); 

      log = new JTextArea(5,20); 
      log.setMargin(new Insets(5,5,5,5)); 
      log.setEditable(false); 
      JScrollPane logScrollPane = new JScrollPane(log); 

      //Create a file chooser 
      fc = new JFileChooser(); 

      //Create the open button. 
      openButton = new JButton("Open a File..."); 
      openButton.addActionListener(this); 

      JPanel buttonPanel = new JPanel(); 
      buttonPanel.add(openButton); 

      //Add the buttons and the log to this panel. 
      add(buttonPanel, BorderLayout.PAGE_START); 
      add(logScrollPane, BorderLayout.CENTER); 
     } 

     public void actionPerformed(ActionEvent e) { 

      //Handle open button action. 
      if (e.getSource() == openButton) { 
       int returnVal = fc.showOpenDialog(FileChooser2.this); 

       if (returnVal == JFileChooser.APPROVE_OPTION) { 
        File file = fc.getSelectedFile(); 
        log.append("Opening: " + file.getName() + "." + newline); 
       } else { 
        log.append("Open command cancelled by user." + newline); 
       } 
       log.setCaretPosition(log.getDocument().getLength()); 
      } 
     } 

     protected static ImageIcon createImageIcon(String path) { 
      java.net.URL imgURL = FileChooser2.class.getResource(path); 
      if (imgURL != null) { 
       return new ImageIcon(imgURL); 
      } else { 
       System.err.println("Couldn't find file: " + path); 
       return null; 
      } 
     } 
     private static void createAndShowGUI() { 
      //Create and set up the window. 
      JFrame frame = new JFrame("PDF Viewer"); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

      //Add content to the window. 
      frame.add(new FileChooser2()); 

      //Display the window. 
      frame.pack(); 
      frame.setVisible(true); 
     } 

     public static void main(String[] args) { 
      SwingUtilities.invokeLater(new Runnable() { 
       public void run() { 
        UIManager.put("swing.boldMetal", Boolean.FALSE); 
        createAndShowGUI(); 
       } 
      }); 
     } 
     public class pdfFilter { 
      //PDF Filter using extension 
      public boolean accept(File f) { 
       if (f.isDirectory()){ 
        return true; 
       } 
       String extension = Utils.getExtension(f); 
       if (extension != null) { 
        if (extension.equals(Utils.pdf)){ 
         return true; 
        } else { 
         return false; 
        } 
       } 
       return false; 
      } 

     } 
    } 

и это класс utils.java, который должен настроить Pdf фильтр

package pdfView; 
import java.io.File; 


public class Utils { 
    //get file name work with pdfFilter.java 
    public final static String pdf = "PDF"; 

    public static String getExtension(File f) { 
     String ext = null; 
     String s = f.getName(); 
     int i = s.lastIndexOf('.'); 

     if (i > 0 && i < s.length() - 1) { 
      ext = s.substring(i+1).toLowerCase(); 
     } 
     return ext; 
    } 

} 
+2

Вы преобразовываете расширение в нижний регистр, а затем сравниваете его с «PDF» - который является прописным. –

+0

Я не понимаю, о чем вы говорите. –

+2

В Utils.getExtension() вы делаете это: 'ext = s.substring (i + 1) .toLowerCase();'. Но Utils.pdf является «PDF» –

ответ

2

изменить эту строку:

extension.equals(Utils.pdf)... 

To:

extension.equalsIgnoreCase(Utils.pdf) 

Вы сравниваете «pdf» с «PDF». это сравнение ascii. если вы хотите, чтобы буквенно-цифровое сравнение использовало вышеуказанный код :)

+0

ok Я завершил это действие, и он по-прежнему не ищет файлы только .pdf extenstion –

+1

ну, вы никогда не устанавливаете фильтр. попробуйте 'fc.setFileFilter (new pdfFilter())' в вашем конструкторе. –

+0

Извините, если я звук немного noobish, но где бы я помещал этот код точно. Я немного новичок в java –