使用 ActionListener 将文件读入 JTextArea

Using ActionListener to Read a File Into a 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() );
}