首页 > 解决方案 > 在 JFrame 中导入整个文本文件

问题描述

我对Java有点陌生。我正在创建一个简单的程序来读取文本文件并将其内容放入 java swing frame 中的文本区域。我的文件看起来像这样

Hello World!
What a beautiful World!

对于 java 框架,我创建了一个按钮和一个按钮操作,以便在单击时将文本文件中的文本导入文本区域。问题是程序只读取了文本文件“多么美丽的世界!”的第二行。我知道这可能是一个小小的愚蠢错误,但我无法弄清楚。这是我的课程代码

import java.io.*;
import java.util.*;

public class JavaGui {

    Scanner scnr;
    static String fileText;

    public void openfile(){
        try{
            scnr = new Scanner(new File("C:\\Users\\13195\\New JavaGui\\abc.txt"));
        }
        catch (FileNotFoundException e){
            System.out.println("File Not Found. Try Again!");
        }
    }

    public void readfile(){
         while (scnr.hasNextLine()){
             fileText = scnr.nextLine();
             System.out.println(fileText);
         }
        scnr.close();
    }
}

这是具有 main 方法的类:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GuiFrame implements ActionListener {
    private JTextArea jtxt = new JTextArea(30, 30);
    private JFrame fr = new JFrame("Framework");
    private JButton btn = new JButton("View Text");

    static String t;

    public GuiFrame(){
        fr.add(jtxt);
        btn.addActionListener(this);
        fr.add(btn);

        //Frame
        fr.setLayout(new FlowLayout());
        fr.setSize(50,50);
        fr.setVisible(true);
    }

    public static void main(String[] args) {
        new GuiFrame();

        JavaGui fr = new JavaGui();
        fr.openfile();
        fr.readfile();

        t = JavaGui.fileText;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btn){
            jtxt.setText(t);
        }
    }
}

标签: javaswingfile-ioiojtextarea

解决方案


推荐阅读