【问题标题】:Displaying whatever has been read from a file in a GUI在 GUI 中显示从文件中读取的任何内容
【发布时间】:2012-11-03 19:25:55
【问题描述】:

所以,我的数据存储在一个名为 log.txt 的文件中,我想在 GUI 中查看它的内容。所以我有这两个我正在使用的类,一个是 Engine,我在其中读取 log.txt 文件,另一个是 GUI,用于应用 Engine 中使用的方法。

所以,在我的引擎中,我有这些代码:

public void loadLog()
    {
        try
        {
            java.io.File cpFile = new java.io.File( "log.txt" );

            if ( cpFile.exists() == true )
            {
                File file = cpFile;

                FileInputStream fis = null;
                BufferedInputStream bis = null;
                DataInputStream dis = null;

                String strLine="";
                String logPrint="";

                fis = new FileInputStream ( file );

                // Here is BufferedInputStream added for fast reading
                bis = new BufferedInputStream ( fis );
                dis = new DataInputStream ( bis );

                // New Buffer Reader
                BufferedReader br = new BufferedReader( new InputStreamReader( fis ) );

                while ( ( strLine = br.readLine() ) != null )
                {
                    StringTokenizer st = new StringTokenizer ( strLine, ";" );

                    while ( st.hasMoreTokens() )
                    {
                        logPrint       = st.nextToken();
                        System.out.println(logPrint);

                    }

                    log = new Log();
                    //regis.addLog( log );




                }
            }

        }
        catch ( Exception e ){
        }
    }

然后,在我的 GUI 中,我会尝试应用在我的引擎中使用的代码:

                    // create exit menu
        Logout = new JMenu("Exit");

        // create JMenuItem for about menu
        reportItem   = new JMenuItem ( "Report" );

        // add about menu to menuBar
        menuBar.add ( Logout );
        menuBar.setBorder ( new BevelBorder(BevelBorder.RAISED) );

        Logout.add ( reportItem );

    /* --------------------------------- ACTION LISTENER FOR ABOUT MENU ------------------------------------------ */

        reportItem.addActionListener ( new ActionListener()
        {
            public void actionPerformed ( ActionEvent e )
            {

                    engine.loadLog();
                    mainPanel.setVisible (false);
                    mainPanel = home();
                    toolBar.setVisible(false);
                    vasToolBar.setVisible(false);
                    cpToolBar.setVisible(false);
                    add ( mainPanel, BorderLayout.CENTER );
                    add ( toolBar, BorderLayout.NORTH );
                    toolBar.setVisible(false);
                    mainPanel.setVisible ( true );
                    pack();
                    setSize(500, 500);
            }
        });

现在,

我的问题是,如何在 GUI 部分中打印出引擎方法中读取的任何内容?我希望它们位于 JLabel 或 JTextArea 内。我该怎么做?

【问题讨论】:

  • 一般的经验法则,如果你打开它,你就关闭它。您应该确保在 finally 块内关闭文件资源 - 恕我直言

标签: java swing user-interface


【解决方案1】:

文件 IO 操作被认为是阻塞/耗时的。

您应该避免在事件调度线程中运行它们,因为这会阻止 UI 开始更新,使您的应用程序看起来像挂起/崩溃

您可以使用SwingWorker 执行文件加载部分,将每一行传递给publish 方法并通过process 方法将这些行添加到文本区域...

public class FileReaderWorker extends SwingWorker<List<String>, String> {

    private final File inFile;
    private final JTextArea output;

    public FileReaderWorker(File file, JTextArea output) {
        inFile = file;
        this.output = output;
    }

    public File getInFile() {
        return inFile;
    }

    public JTextArea getOutput() {
        return output;
    }

    @Override
    protected void process(List<String> chunks) {
        for (String line : chunks) {
            output.append(line);
        }
    }

    @Override
    protected List<String> doInBackground() throws Exception {
        List<String> lines = new ArrayList<String>(25);
        java.io.File cpFile = getInFile();
        if (cpFile != null && cpFile.exists() == true) {
            File file = cpFile;

            BufferedReader br = null;

            String strLine = "";
            String logPrint = "";
            try {
                // New Buffer Reader
                br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                while ((strLine = br.readLine()) != null) {
                    StringTokenizer st = new StringTokenizer(strLine, ";");
                    while (st.hasMoreTokens()) {
                        logPrint = st.nextToken();
                        publish(logPrint);
                    }
                }
            } catch (Exception e) {
                publish("Failed read in file: " + e);
                e.printStackTrace();
            } finally {
                try {
                    if (br != null) {
                        br.close();
                    }
                } catch (Exception e) {
                }
            }
        } else {
            publish("Input file does not exist/hasn't not begin specified");
        }            
        return lines;
    }
}

查看Lesson: Concurrency in Swing了解更多信息

【讨论】:

  • @HovercraftFullOfEels 这是一个公平的昵称选择,但这就是为什么我将它包装在一个空的 try-catch 中,这是我唯一一次不在乎 - 我想尽最大努力确保我关闭文件资源
  • 评论已删除。我已建议 OP 听取您的建议。说得好。
  • 这个疯子又帮我了,我记得你!我会的。非常感谢 Hovercraft 和 MadProgrammer :)
【解决方案2】:

也许您希望您的 loadLog 方法返回一个字符串,该字符串包含它从文件中读取的文本,然后在 GUI 中调用该方法并根据需要显示返回的字符串。另外,在执行 I&O 时,永远不要有一个空的 catch 块。

【讨论】:

  • 这就是我一直在尝试的。但它不起作用:/我在我的引擎类中做 GUI 部分并尝试调用它,它不起作用。我尝试在我的引擎类中获取一个字符串,并尝试在我的 GUI 类中将其用作 GUI,仍然。你能更具体地说明如何做这件事吗?谢谢。
  • @SBOY:您似乎没有将该方法定义为 return 一个字符串,所以它是有道理的,因为写它赢了不行。再次,更改方法,使其返回一个字符串,而不是当前编写的 void。然后在 GUI 中,将该字符串接受为字符串变量。
  • @SBOY:但 MadProgrammer 的建议更完整、更正确。我建议你听从他的建议并接受它。
【解决方案3】:

如果我误解了你的问题,请原谅我,但这里什么都没有:

您将要逐行读取文本文件,并将每一行添加到 JTextArea。

        BufferedReader reader = new BufferedReader(new FileReader("pathToFile"));  //This code creates a new buffered reader with the specified file input.  Replace pathToFile with the path to your text file.
        String text = reader.readLine();
        while(text != null) {
        myTextArea.append("\n" + text);  //Replace myTextArea with your JTextArea
        text = reader.readLine();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2016-01-05
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多