I want to create a JTextArea
in a Java Swing frame that reads the contents of a file when I click on a button. I created a JButton
, the text area and added an ActionListener
for the button, but I don't know how to make the actionPerformed
method to read the file after clicking the button.
Here's my code:
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?
}
}
Something like this will do
@Override
public void actionPerformed( ActionEvent e )
{
if( e.getSource() == btn ) // your button
{
doAction();
}
}
doAction()
contains the logic you need to run when you click on the button reference 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() );
}