在 java swing Gui 中显示“.txt”文件时遇到问题。
我有读取 .txt 文件并将其显示在 cmd 窗口中的代码,但似乎无法链接它,因此它将显示在 Gui 中。
这是读取文件的代码:
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
这是 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);
}
}
这是运行 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);
}
}
所有文件与 .txt 文件都位于我的笔记本电脑上的同一文件夹中。我正在使用 TextPad 进行编码和编译。
非常感谢所有帮助
谢谢 德里克
最佳答案
here is the code that reads the file:
删除该代码,不需要。
JTextArea 有一个 read(...)
方法,可用于将文本文件直接读入文本区域。
关于java - 在 java swing GUI 中显示文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15602104/