【发布时间】:2013-03-24 18:08:16
【问题描述】:
在 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 进行编码和编译。
所有的帮助都会得到满足
谢谢 德里克
【问题讨论】:
-
读取文件的所有代码都在
main()中运行...这不是您想要的。您宁愿创建完全执行此操作的方法,但不在main()中。 -
是的,这正是我想做的 Makoto。但是当我尝试这样做时,我得到了一个错误。
标签: java swing filereader