【问题标题】:Swing Java GUI reading a text file with scannerSwing Java GUI 使用扫描仪读取文本文件
【发布时间】:2014-09-25 09:31:00
【问题描述】:

我正在尝试构建一个 GUI 应用程序,它会在按下按钮时读取文本文件 然后将此文件的内容保存到字符串中。我当前的代码,我基本上尝试为 gui 调整我的控制台代码,但它似乎不起作用。这是我的按钮代码:

 private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              


    Scanner user_input = new Scanner(tempTextField.getText());

    String seq1 = user_input.next();

    Scanner scanner = new Scanner(new File(seq1));
    scanner.nextLine();
    String content = scanner.useDelimiter("\\Z").next();


    int N = content.length();

    textarea.append("Length of the input string is: "+N);
}

textarea = JtextArea tempTextField = JTextField

谢谢。 编辑:我正在使用 netbeans IDE

【问题讨论】:

  • “它似乎不起作用”是什么意思?
  • 哦,是的,对不起。未报告的异常是错误,它不会编译。

标签: java swing user-interface io


【解决方案1】:

你必须处理来自Scanner scanner = new Scanner(new File(seq1))的异常:

private void convertButtonActionPerformed(java.awt.event.ActionEvent evt)        
{                                              
Scanner user_input = null;
Scanner scanner = null;
try
{
user_input = new Scanner(tempTextField.getText());

String seq1 = user_input.next();


scanner = new Scanner(new File(seq1));
scanner.nextLine();
String content = scanner.useDelimiter("\\Z").next();


int N = content.length();

textarea.append("Length of the input string is: "+N);
}catch(FileNotFoundException e)
{
 e.printStackTrace();
}finally
{
 //always close scanner
 if(user_input != null)
    user_input.close();

  if(scanner  != null)
    scanner.close();



}
}

【讨论】:

  • 非常感谢。这正是我想要的。
【解决方案2】:

这些被称为“检查异常”。在这里,编译器会强制您处理 try/catch 块中的此类代码,即报告异常,然后您才能继续执行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多