java - 在 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);
}
}
}
解决方案
推荐阅读
- reactjs - React 中 reducer 的执行顺序
- javascript - 页面加载时的 css (box-shadow) 过渡
- python - 在 Pandas DataFrame 列表中查找月份和年份的最大日期
- android - Android Jetpack 导航禁用滚动位置
- javascript - 在javascript中计算iso时间格式的时差?
- javascript - npm install lite-server --save-dev 安装错误
- android - 如何在我的贴纸应用程序中单击“查看更多”按钮并将其与我在 Android 中的 Playstore 应用程序链接
- c++ - 使用 cin 读取空行
- java - 如何在安卓应用中设置最大音量?
- jenkins - FAILURE:构建完成,有 4 次失败