【发布时间】:2016-04-07 11:43:22
【问题描述】:
我目前正在开展一个项目,该项目显示学生可能注册的课程的 JList。
单击列表项时,将一个变量传递给 setTextArea() 方法以获取 txt 文件名。
例如,如果我单击计算机科学,则会传递一个 courseName 变量并将其插入到 URL 以检索 txt 文件。
这工作得很好。除非我使用 JAR 文件。我知道在使用 JAR 时必须使用 .getClass() 和 getResource() 来访问资源,但我似乎无法让我的工作。
这是我的原始代码。
public void valueChanged(ListSelectionEvent e)
{
int selectionNum = courseList.getSelectedIndex();
String courseName;
//Switch statement to pass strings to method
switch(selectionNum)
{
case 0: courseName = "computer_science";
setTextArea(courseName);
currentCourseClicked ="0";
break;
case 1: courseName = "business";
setTextArea(courseName);
currentCourseClicked ="1";
break;
case 2: courseName = "business2";
setTextArea(courseName);
currentCourseClicked ="2";
break;
case 3: courseName = "engineering";
setTextArea(courseName);
currentCourseClicked ="3";
break;
case 4: courseName = "sport";
setTextArea(courseName);
currentCourseClicked ="4";
break;
case 5: courseName = "early";
setTextArea(courseName);
currentCourseClicked ="5";
break;
case 6: courseName = "social";
setTextArea(courseName);
currentCourseClicked ="6";
break;
}
} //End of valuesChanges Method
/**
* This method is used to read the file, with the course name passed
* from the valueChanged method.
* @param courseName
*/
@SuppressWarnings("resource")
public void setTextArea(String courseName)
{
descriptionPanel.setVisible(true);
enrol.setVisible(true);
enrol.setFont(new Font("", Font.BOLD, 20));
try
{
//This retrieves the information from a text file
FileReader file = new FileReader("./res/courseInfo/" +courseName + ".txt");
Scanner fileReaderScan = new Scanner(file);
String storeAll = "";
//while loop to read trough lines of the text file
while(fileReaderScan.hasNextLine())
{
String temp = fileReaderScan.nextLine() + "\n";
storeAll += temp;
}
descriptionTextArea.setText(storeAll);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
} //end of setTextArea method
然后我尝试使用 getClass 和 getResource,但它不适用于 URL,并要求我将 URL 类型更改为 String。如果我这样做,那么 getClass 和 getResource 将不起作用。
我后来尝试使用 String urlString = url + ""; 将 url 连接到字符串,但这也没有用。
关于如何解决这个问题的任何想法?
【问题讨论】:
-
您的资源到底在哪里?在你的 jar 文件中?如果有,具体在哪里?
-
因为 url 在 FileReader 中不起作用。它要求将
url转换为字符串类型。但是当我这样做时,getClass().getResource 不起作用。 -
“除了我使用 JAR 文件时”是什么意思?
-
@aribeiro 当我使用 eclipse 时,我可以在 JTextArea 中查看 txt 文件的内容。但是,如果我使用 jar 文件,它将无法工作,显然是因为它正在寻找仅适用于 eclipse 的路径。因此,jar文件无法访问资源文件夹中的txt文件。
-
请按照@Hackerdarshi 的回答。
标签: java file user-interface jar