java - 使用 ActionListener 将文件读入 JTextArea

标签 java swing file-io actionlistener jtextarea

我想在 Java Swing 框架中创建一个 JTextArea,当我单击按钮时,它会读取文件的内容。我创建了一个 JButton、文本区域,并为该按钮添加了一个 ActionListener,但我不知道如何使 actionPerformed 方法单击按钮后读取文件。

这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Scanner;

public class JavaGui extends JFrame implements ActionListener {
    JButton btn;
    JTextArea jtxt = new JTextArea(50, 50);

    public JavaGui() {
        super("This is the Title");
        setLayout(new FlowLayout());
        btn = new JButton("Click Here");
        btn.addActionListener(this);
        add(btn);
        add(jtxt);
    }

    public static void main(String[] args) throws IOException {
        //Open file for reading content
        FileInputStream file = new FileInputStream("abc.txt");
        Scanner scnr = new Scanner(file);
        System.out.println(file.nextLine());

        //Create the JFrame window
        JavaGui obj = new JavaGui();
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.setSize(500, 500);
        obj.setVisible(true);
    }

    public void actionPerformed(ActionEvent e){
        // how to do this? 
    }
}

最佳答案

像这样就可以了

@Override
public void actionPerformed( ActionEvent e )
{
    if( e.getSource() == btn ) // your button 
    {
        doAction();
    }
}

doAction() 包含单击按钮引用 btn

时需要运行的逻辑
void doAction()
{
    StringBuilder sb = new StringBuilder();
    try( BufferedReader br = Files.newBufferedReader( Paths.get( "filename.txt" ) ) )
    {
        String line;
        while( ( line = br.readLine() ) != null )
        {
            sb.append( line ).append( "\n" );
        }
    }
    catch( IOException e )
    {
        System.err.format( "IOException: %s%n", e );
    }
    jtxt.setText( sb.toString() );
}

关于java - 使用 ActionListener 将文件读入 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62420888/

相关文章:

java - 自定义 boolean 反序列化器在 Gson 中不起作用

java - 发生某种情况后停止线程 ScheduledThreadPoolExecutor

java - BasicPopupMenuUI 错误

java - 使用javaFx TableView 显示选定行的内容

java - getAudioInputStream 格式无效,尝试在 Java 中播放声音

swing - 设置 ContentPane 的大小(在 JFrame 内部)

c# - 将文本文件与 C# 中的文本模式进行比较?

c - 当我在 linux 下的 c 套接字中使用 read() 和 write() 时尺寸缩小

android - IOException - 无法加载文件

java - 列出 Maven 存储库中的所有 Artifact