【问题标题】:Display file in java swing GUI在 java swing GUI 中显示文件
【发布时间】: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


【解决方案1】:

这是读取文件的代码:

去掉那个代码,不需要它。

JTextArea 有一个read(...) 方法,您可以使用该方法将文本文件直接读入文本区域。

【讨论】:

  • 试过myArea.read(Reader, "player.txt"); 我在哪里设置文本区域但一直出错??是我用read( )错了吗??
  • 是的,您使用的方法错误。您仍然需要像以前那样创建 BufferedReader。然后你只需使用textArea.read(br, null);
【解决方案2】:

您可以在Actionlistener 类中创建ReadFile 类的对象并调用ReadFile 的main 方法。

【讨论】:

  • 感谢 Vineet 的帮助,创建对象后如何在 Gui 中显示它??
  • 此后您可以使用JLabel 在 GUI 中显示所有数据。
  • 您不能使用 JLabel 显示多行文本(除非 HTML 文件中的文本)。
猜你喜欢
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多