2013-01-14 36 views
0

我的扫描仪出现问题。点击按钮,应显示来自第二个文件的文本。我得到了按钮的工作,但程序直接跳到新文本文件的最后一行。由于加载时间较慢,我认为这是因为我无法关闭我的第一台扫描仪。我认为我的布局不是很重要,因为一次只能读取很多文本文件,但将第二个类作为内部类编写会让事情看起来更加复杂。关闭扫描仪,但需要从另一个类访问

如何使第二类扫描仪可以访问第一类(并因此使用reader.close())? 我应该使用嵌套/内部类来启动程序吗? 是否有一种更清洁的方法来启动程序,然后为扫描仪启动后续操作?

最后,我一直在努力符合SSCCE,我有什么亲密吗?感谢您的帮助

import declarations 
public class MihatteFrame extends JFrame implements ActionListener{ 
.... 
public MihatteFrame() { 
    area 
    textfield 
    button 
} 
displayText method 
checkTextFieldText method 

public void actionPerformed(ActionEvent e) { 
    try { 
     if (textField.getText().equals("proceed to the entrance")) { 
      Scanner.close(); 
      Scanner reader2 = new Scanner(new File("(Start) Front Gate.txt")); 
      while (reader2.hasNextLine()) { 
       String line = reader2.nextLine(); 
       displayText(line); 
       try { 
        if(!line.trim().equals("")){ 
           Thread.sleep(1000); 
         } 
        } catch (InterruptedException e) { 
        } 
      } 
     } else { 
      while (textField.getText() == null) { 
       displayText("I`m sorry, could you say that again?"); 
      } 
     } 
    } catch (IOException ioe) { 
    } 
} 

X

import declarations 
class ShowIntro { 
public static void main(String args[]) throws IOException { 
MihatteFrame mf = new MihatteFrame(); 
Scanner reader = new Scanner(new File("(Start) Introduction.txt")); 

while (reader.hasNextLine()) { 
    String line = reader.nextLine(); 
    mf.displayText(line); 
    try { 
     if(!line.trim().equals("")){ 
     Thread.sleep(1000); 
      } 
    } catch (InterruptedException e) { 
    }  
} 
+0

我怀疑这甚至没有编译'Scanner.close();' –

+0

在SSCCE上越来越近,但是'....'表示阻止它成为SSCCE的问题区域。 –

回答

2

GUI线程,当你从它调用你一个事件只返回执行动作。这意味着如果你做了很多动作,你只会看到这些动作的累积,如果你因任何原因暂停,你的GUI将会暂停。

您需要在另一个线程中执行该操作,以便GUI线程可以更新屏幕。您还需要使用SwingUtils.invokeLater()从第二个线程更新GUI。

+2

试试这个教程: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html – flup

+1

只是想说感谢你的意见和教程 - 我仍然阅读和处理它,所以可能随后qs后续。 –