[英]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() );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.