需要帮助,需要使用setText()在jpanel上读取文件并显示内容

时间:2020-07-09 22:16:32

标签: java swing user-interface filereader

在Netbeans上,

我试图读取文件并将其内容显示在swing图形选项卡上。我就是这样读取文件的

    FileReader reader;
    ArrayList<String> file = new ArrayList<String>();
    Scanner scan = null;
    try 
    {
        reader = new FileReader(filename);
        scan = new Scanner(reader);
        
        
        while(scan.hasNext())
        {
            file.add(scan.nextLine());
        }

        return file;
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally {
        scan.close();
    }

    return null;

这就是我写文件的方式

public String writeFile(ArrayList<String> data)
{
    String writer = "";
    for (String line : data)
    {
        writer += (line + lineSeparator);
    }
    return writer;
    }

这就是我要显示的方式

FileIO file = new FileIO();
    String filePath="squeeze.txt";
    ArrayList<String> data = file.readFile(filePath);
    jTextField1.setText(file.writeFile(data));

我收到一个错误消息

scan.close();

2 个答案:

答案 0 :(得分:0)

您的问题是 public String getLargestWord(Node root) { if (root.isLeaf()) { return String.valueOf(root.getValue()); } else { String longest = ""; for (Node child : root.getChildren()) { String longWordInChild = getLongestWord(child); if (longWordInChild.length() > longest.length()) { longest = longWordInChild; } } return root.getValue() + longest; } } 在try块之前尚未初始化。 try块中的任何内容都可能引发异常,因此,您必须编写代码,并假定try块中的所有代码都将永远不会运行。幸运的是,Java针对这种情况使用了一种名为try-with-resources的语法。 Try-with-resources为您处理资源,并在try块结束时自动将其关闭。这是您的代码,已修改为使用try-with-resources:

scan

我还注意到,在您的catch块中,您只需打印堆栈跟踪。就语法而言,这是完全可以的,编译器会接受它,但是我不建议您吞下这样的错误。如果您不想做任何特别的事情,那么您可以使用的最佳通用行是try (FileReader reader = new FileReader(filename); Scanner scan = new Scanner(reader)) { while(scan.hasNext()) { file.add(scan.nextLine()); } return file; } catch (IOException e) { e.printStackTrace(); } return null; 。这只会引发一般的运行时异常,该异常将打印堆栈跟踪,然后终止程序。这还具有一个额外的好处,即您不需要底部的throw new RuntimeException();行,因为运行时异常无论如何都会退出程序,然后任何调用此方法的方法都可以安全地假定此方法返回一个非-空值。

答案 1 :(得分:0)

jTextField1.setText(file.writeFile(data));

JTextField用于单行文本。对于多行,请使用JTextArea

关于眼前的问题,最简单的解决方案是使用任何JTextComponent(包括上述两个方法)可用的方法。

分别是JTextComponent.read(Reader,Object)JTextComponent.write(Writer)