我正在开发一个特定于PDF的文件浏览器,并且由于堆栈溢出的帮助,我已经取得了很多进展,我的代码遇到了另外一个问题。我已经制作了创建此文件资源管理器功能所需的所有元素,但这两个类没有正确通信。这是我的代码 包pdfView;
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;
}
}
}
这是应该设置pdf过滤器的utils.java类
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;
}
}
答案 0 :(得分:2)
更改此行:
extension.equals(Utils.pdf)...
要:
extension.equalsIgnoreCase(Utils.pdf)
您正在比较&#34; pdf&#34;到&#34; PDF&#34;。这是一个ascii比较。如果你想要字母数字比较,请使用上面的代码:)