Reputation: 35
Having problems displaying a ".txt" file in a java swing Gui.
I have the code to read the .txt file and display it in the cmd window but cant seem to link it so it will display in the Gui.
here is the code that reads the file:
import java.io.*;
public class ReadFile {
public static void main (String [] args) throws IOException{
String inputLine = "";
FileReader inputFile = new FileReader( "player.txt");
BufferedReader br = new BufferedReader(inputFile);
System.out.println( "\nThe contents of the file player.txt are ");
// Read lines of text from the file, looping until the
// null character (ctrl-z) is endountered
while( ( inputLine = br.readLine()) != null){
System.out.println(inputLine); // Write to the screen
}
br.close(); // Close the stream
} // end of main method
} // end of class
here is the code for the Swing Gui
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class GUI extends JFrame{
private JButton button;
//Set Hight and Width of Interface
private static final int WIDTH = 500;
private static final int HEIGHT = 500;
//Method to Create Inteface
public GUI(){
createComponents();
createDisplay();
setSize(WIDTH, HEIGHT);
}
//An Action Listener To Contorl Action Preformed
class ClickListener implements ActionListener{
public void actionPerformed(ActionEvent event){
}
}
//Method to Create Button
private void createComponents(){
button = new JButton("Click Me");
ActionListener listener = new ClickListener();
button.addActionListener(listener);
JPanel panel = new JPanel();
panel.add(button);
add(panel);
}
//Method To Create Display
private void createDisplay(){
JTextArea myArea = new JTextArea();
JPanel panel1 = new JPanel();
panel1.add(myArea);
add(panel1);
}
}
and here is the code to run the Swing GUI
import javax.swing.*;
public class GUITest{
public static void main (String [] agrs){
JFrame frame = new GUI();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
All files are in the same folder on my laptop along with the .txt file. And i am using TextPad to code and compile.
all help would be grate
thanks Derek
Upvotes: 2
Views: 12812
Reputation: 324118
here is the code that reads the file:
Get rid of that code, it is not needed.
JTextArea has a read(...)
method that you can use to read the text file directly into the text area.
Upvotes: 1
Reputation: 193
You could create an object of the ReadFile
class in the Actionlistener
class and call ReadFile
's main method.
Upvotes: 1