【发布时间】:2018-03-13 17:08:44
【问题描述】:
我创建了两个类,第一个类从文件中读取,第二个类应该使用 java swing 打印文件,但它唯一显示的是 null 我试图使用 String.valueOf(word) 将单词转换为字符串,但是这也不起作用
private static String getFileInfo(){
File listOfWords = new File("words.txt");
try {
BufferedReader getInfo = new BufferedReader(new FileReader(listOfWords));
String word = getInfo.readLine();
while(word!=null) {
System.out.println(word);
word = getInfo.readLine();
}
}
catch(FileNotFoundException e) {
System.exit(0);
}
catch(IOException e){
System.exit(0);
}
return word;
}
public LabelThread() {
try {
JFrame frame = new JFrame("Label");
frame.setSize(500, 500);
textLabel = new JLabel(String.valueOf(word));
frame.setContentPane(textLabel);
frame.setVisible(true);
MyThread thread = new MyThread();
MyThread.sleep(15000); // 15 secondes then 10 then 5
thread.start();
} catch (InterruptedException ex) {
}
}
class MyThread extends Thread{
public void run() {
System.out.print("Running thread");
textLabel.setText("");
}
【问题讨论】:
-
words.txt 必须在项目的根目录中才能使用此声明,否则您需要完整的限定路径名
-
您正在阅读
getFileInfo中的文件,但我没有看到您在任何地方调用该方法。此外,word是getFileInfo中的局部变量,但您将其称为类级别变量。这甚至为你编译吗?最后,您正在尝试将word写入标准输出,是用于调试还是您希望这样做?我的建议是从LabelThread构造函数调用getFileInfo,并将该返回值分配给textLabel。您还需要连接从文件中读取的字符串。
标签: java swing file user-interface text