[英]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.