如何将.txt文件添加到JTextArea以及放置.txt文件的位置?

时间:2014-05-06 23:14:39

标签: java swing jtextarea

我正在处理我的第一个GUI程序并且几乎完成了最后一个类是一个jFrame,它有一个.txt文件和一个关闭窗口的按钮,我不知道如何将我的文件追加到窗户 ??? 包eg.edu.guc.santorini.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Rules extends JFrame implements ActionListener, MouseListener{
JPanel Rules;
JTextArea  rules;
public Rules() throws IOException
{
    super();
    setTitle("Rules Of Santorini Board Game");
    setSize(1000, 700);
    setLocation(200, 100);
    Container content = getContentPane();
    content.setBackground(new Color(220,20,60));
    content.setLayout(new BorderLayout());
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    WindowDestroyer wd = new WindowDestroyer();
    addWindowListener(wd);

    JTextArea  rules=new JTextArea();
    rules.append("");


    JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);

    StringBuilder builder = new StringBuilder();

    // read a text file from resources folder that is parallel to src folder
    BufferedReader reader = new BufferedReader(new FileReader(new               File("resources/New Text Document.txt")));
    String line = null;
    while ((line = reader.readLine()) != null) {
        // read the file line by line
        builder.append(line).append(System.lineSeparator());
    }
    reader.close();

    // set the content of file in text area
    textArea.setText(builder.toString());

       /* FileReader fileReader = new FileReader("New Text Document.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);

String inputFile = "";
String textFieldReadable = bufferedReader.readLine();

while (textFieldReadable != null){
    inputFile += textFieldReadable;
    textFieldReadable = bufferedReader.readLine();                    
    rules.setText(inputFile);*/



    Rules=new JPanel();
    Rules.setLayout(null);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    Rules.setVisible(true);
    Rules.setBackground(Color.ORANGE);
    add(Rules, BorderLayout.CENTER);
    Rules.setSize(1000, 700);
    this.getContentPane().add(Rules);


    JButton ok=new JButton("Got It");
    ok.setSize(100, 50);
    ok.setLocation(800, 570);
    ok.addMouseListener(this);
    Rules.add(ok);

    ok.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
            //dispose();
            setVisible(false);

        }
  });

    //JFrame f = new JFrame();
    //f.setSize(320, 200);
    //f.getContentPane().add(rules);
    //f.setVisible(true);



}




@Override
public void mouseClicked(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

}

2 个答案:

答案 0 :(得分:4)

  

在哪里放置我的.txt文件?

你可以尝试任何一个

// Read from same package 
InputStream in = getClass().getResourceAsStream("abc.txt");

// Read from resources folder parallel to src in your project
File file = new File("resources/abc.txt");

// Read from src/resources folder
InputStream in = getClass().getResourceAsStream("/resources/abc.txt");

enter image description here


- 编辑 -

必须阅读A Visual Guide to Layout Managers

以下是您的代码中的一些要点:

  • 请勿使用null布局Rules.setLayout(null);
  • 添加所有组件后,最后调用JFrame#setVisible(true);
  • 始终使用SwingUtilities.invokeLater()初始化GUI
  • 遵循Java命名约定。

答案 1 :(得分:4)

要将文件读入JTextArea,您只需使用JTextArea#read,但这会丢弃JTextArea

的当前内容

<强>更新

将代码添加到IDE后,我注意到您没有将rulesJTextArea)添加到任何内容中,因此它永远不可见...

您创建UI的一般结构也有点偏斜,尝试更像......

public class Rules extends JFrame {

    public Rules() throws IOException {
        super();
        // Initial setu[
        setTitle("Rules Of Santorini Board Game");

        // Create the basic UI content
        JTextArea textArea = new JTextArea(40, 20);
        JScrollPane scrollPane = new JScrollPane(textArea);

        // Read the file
        try (BufferedReader reader = new BufferedReader(new FileReader(new File("resources/New Text Document.txt")))) {
            textArea.read(reader, "File");
        } catch (IOException exp) {
            exp.printStackTrace();
        }

        getContentPane().setBackground(Color.ORANGE);

        JButton ok = new JButton("Got It");
        add(textArea, BorderLayout.SOUTH);
        add(ok, BorderLayout.SOUTH);

        ok.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //dispose();
                //?? No idea what this is for, but it won't do much
                setVisible(false);

            }
        });

        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);

    }

}

不要将MouseListener用于按钮,而应使用ActionListener

不要使用null布局。像素完美布局是现代UI设计中的一种幻觉,您无法控制字体,DPI,渲染管道或其他因素,这些因素将改变组件在屏幕上呈现的方式。

Swing旨在与布局管理员合作以克服这些问题。如果你坚持忽略这些功能并违背API设计,那就要做好准备应对很多令人头疼的事情,永远不要过时努力......