3
我创建一个JFile选择器,并使用.setCurrentDirectory();通过传递newFile(“。”)将Directory设置为我的java项目文件夹的根目录。这似乎有时工作得很好,但有时它会引发错误。这一切都发生在程序加载时,在任何用户输入之前,因为据我所知,它是完全随机的,无论它是否发生。这里是我的代码的文件选择相关的位:JFile选择器在使用前抛出错误,有时只有?
public class PnlHighScores extends JPanel {
JFileChooser fcScores = new JFileChooser();
PnlHighScores() {
fcScores.addChoosableFileFilter(new TxtFilter());
//***********This seems to cause a strange error only somethimes, Right as the program is run!***********
fcScores.setCurrentDirectory(new File("."));//http://www.rgagnon.com/javadetails/java-0370.html
}
class ActFileChooser implements ActionListener {
public void actionPerformed(ActionEvent e) {//http://download.oracle.com/javase/tutorial/uiswing/examples/components/FileChooserDemoProject/src/components/FileChooserDemo.java
int returnVal = fcScores.showOpenDialog(PnlHighScores.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
filScores = fcScores.getSelectedFile();
sFileLocation = filScores.getAbsolutePath();//.getParent();//http://www.java-forums.org/awt-swing/29485-how-retrieve-path-filechooser.html
//System.out.println(filScores);
pnlScoreText.updateScoreFile(sFileLocation);
}
}
}
class TxtFilter extends javax.swing.filechooser.FileFilter {//http://www.exampledepot.com/egs/javax.swing.filechooser/Filter.html
public boolean accept(File file) {
String filename = file.getName();
if (file.isDirectory()) {
return true;
} else {
return filename.endsWith(".txt");
}
}
public String getDescription() {
return "*.txt";
}
}
}
确切的错误是:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Invalid index
at javax.swing.DefaultRowSorter.convertRowIndexToModel(DefaultRowSorter.java:497)
at sun.swing.FilePane$SortableListModel.getElementAt(FilePane.java:528)
at javax.swing.plaf.basic.BasicListUI.updateLayoutState(BasicListUI.java:1343)
at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(BasicListUI.java:1294)
at javax.swing.plaf.basic.BasicListUI.getCellBounds(BasicListUI.java:935)
at javax.swing.JList.getCellBounds(JList.java:1600)
at javax.swing.JList.ensureIndexIsVisible(JList.java:1116)
at sun.swing.FilePane.ensureIndexIsVisible(FilePane.java:1540)
at sun.swing.FilePane.doDirectoryChanged(FilePane.java:1466)
at sun.swing.FilePane.propertyChange(FilePane.java:1513)
at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:339)
at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:276)
at java.awt.Component.firePropertyChange(Component.java:8128)
at javax.swing.JFileChooser.setCurrentDirectory(JFileChooser.java:568)
at Cannon.PnlSettings.<init>(PnlSettings.java:45)
at Cannon.FraWindow.<init>(FraWindow.java:19)
at Cannon.Main.main(Main.java:7)
Java Result: 1
主类简单的创建FraWindow,并通过FraWindow它的构造方法创建PnlSetting。他们应该是irrelavent,但这里的主要以防万一:
package Cannon;
//Creates the frame
public class Main {
public static void main(String[] args) {
FraWindow fraMain = new FraWindow();
}
}
究竟是什么引发的异常? – jerluc 2011-01-22 04:54:19
我们可以看到主班吗? – 2011-01-22 05:28:55