在启动时将文件打开到JTextArea

时间:2014-05-08 02:48:30

标签: java user-interface text file-io jtextarea

我有一个程序,我正在尝试测试是否创建了一个文件(info.txt),如果是,则在程序启动时将内容打开到JTextArea中。我该怎么做呢? 香港专业教育学院已经想出如何搜索并查看文件是否存在,只是无法让它在启动时打开到textArea

import javax.swing.*; // need it
import java.awt.*;   //need it also
import java.awt.datatransfer.*;
import java.util.*;
import java.io.*;
import java.awt.event.*; //keeps track of events
import javax.swing.border.*; // not necessary / already imported ^^

import javax.swing.*; 
import java.awt.*;   
import java.awt.datatransfer.*;
import java.util.*;
import java.io.*;
import java.awt.event.*; 
import javax.swing.border.*;

public class finalA extends JFrame implements ActionListener{
 private final int WIDTH = 750;
 private final int HEIGHT = 400;
 static String theText;
 private String text;

 //creates components
 private JTextArea textArea;
 private JButton SaveB;
 private JScrollPane scroll;


 public finalA(){
 setTitle("Super fancy text editor");
 setSize(WIDTH,HEIGHT);

  Container pane = getContentPane();

  //Creates button
  SaveB = new JButton("Save & Exit");
  textArea = new JTextArea();
  scroll = new JScrollPane(textArea);
  scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

  //adds event handler for exit button

  SaveB.addActionListener(this);

  //sets pane to null
  pane.setLayout(null);

  //location of button and TA (750,400)
  textArea.setLocation(10,100);
  SaveB.setLocation(150,320);

  //set size of TA and Button
  textArea.setSize(730,200);
  SaveB.setSize(100,30);

  //add items to pane
  pane.add(textArea);
  pane.add(SaveB);

  scroll.setBounds(10,100,730,200);
  scroll.setVisible(true);

  textArea.setLineWrap(true);
  textArea.setWrapStyleWord(true);
  setDefaultCloseOperation(EXIT_ON_CLOSE);
  }//ends constructor

  public void openFile()throws Exception{
   File f = new File("info.txt");
   if(f.exists()){
    FileReader reader = null;
    try{
     reader = new FileReader("info.txt");
     textArea.read(reader, null);
    } 
    finally{
     if (reader != null){
        reader.close();
     }
    }
   }
  }//ends openFile

  public void actionPerformed(ActionEvent e){
   String text = textArea.getText();
   if(e.getActionCommand().equals("Save & Exit")){

    try{
     BufferedWriter reader = new BufferedWriter(new FileWriter(new File("info.txt"),true));
     reader.write(text);
     reader.newLine();
     reader.close();
    }catch(IOException E){
    System.out.println("the error is " + E);
    }
   }
   System.exit(0);



 } 
}// ends finalA class

3 个答案:

答案 0 :(得分:1)

因此,根据您的可用代码,您只需在构建者的末尾调用openFile,然后再创建JTextArea

public TestRead() {
    //...
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    try {
        openFile();
    } catch (IOException exp) {
        exp.printStackTrace();
    }
}//ends constructor

不要使用null布局,像素完美布局是现代GUI设计中的错觉。您无法控制字体指标,DPI或渲染管道等因素,所有这些因素都可能会改变组件的个性化需求。

Swing旨在使用布局管理器,并且更新接口的大部分功能都与它相关。如果您取消布局管理器,请准备好承受永无止境的工作和挫折

答案 1 :(得分:0)

使用文件阅读器流(如Scanner)加载文件,然后将文本附加到文本区域。

这是一个简单的演示:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
/*
* simple demo to load file to textarea
*/
public class FileLoaderTest {
    public static void main(String[] args) throws IOException{
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                JFrame frame = new JFrame("Load File Demo");
                JPanel panel = new JPanel();
                JButton btnLoad = new JButton("Load File");
                final JTextArea textArea = new JTextArea(10,20);
                btnLoad.addActionListener(new ActionListener(){

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub
                        JFileChooser fileChooser = new JFileChooser();
                        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
                        fileChooser.setFileFilter(new FileNameExtensionFilter
                                  ("Text File", "txt"));
                        fileChooser.setAcceptAllFileFilterUsed(false);
                        while(true)
                        {
                            if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ) {

                                if(!fileChooser.getSelectedFile().exists()) {
                                    JOptionPane.showMessageDialog(fileChooser, 
                                            "You must select an existing file!","open File",
                                            JOptionPane.ERROR_MESSAGE);//continue
                                }else {
                                    //read file to the textArea
                                    File file = fileChooser.getSelectedFile();
                                    try {
                                        Scanner scanner = new Scanner(new  BufferedReader
                                                   (new FileReader( file)));
                                         while(scanner.hasNext()) {
                                             textArea.append(scanner.nextLine()+"\n");
                                          }
                                         scanner.close();
                                    } catch (FileNotFoundException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                    }
                                    break;//successfully open break
                                }
                            }else {
                                break;//user cancel open break
                            }
                        }
                    }
                });
                JScrollPane scrollPane = new JScrollPane(textArea);
                panel.add(btnLoad);
                frame.add(panel,BorderLayout.NORTH);
                frame.add(scrollPane,BorderLayout.CENTER);
                frame.setSize(400, 400);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

答案 2 :(得分:0)

从你的问题我认为你已经走到了这一步:

BufferedReader in = null;
    try{
        in = new BufferedReader(new FileReader("C:\\path\\to\\file\\info.txt"));
        String str = in.readLine();
        ArrayList<String> textList = new ArrayList<String>();
        while((str = in.readLine()) != null){
            textList.add(str); //saves each line that is read from the file
        }

        //-->This is where you will add later code

    }catch(IOException e){
        System.out.println("Error reading file");
        e.printStackTrace();
    }

从这里开始,您应该使用

JTextArea.append()
方法,如下所示:

- 在readFile()方法中的while循环后插入。

for(String s:textList){
    yourJTextArea.append(s +"\n");
}

一个完整的例子:

import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JTextArea;


public class TextRead extends JFrame{

    static JTextArea mytextArea;

    public TextRead(){
        super("TextRead");

        mytextArea = new JTextArea();
        mytextArea.setPreferredSize(new Dimension(500,500));

        getContentPane().add(mytextArea);

        setContentPane(getContentPane());

        pack();
        setVisible(true);
        setSize(500,500);
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        readFile();
    }

    private void readFile() {
        BufferedReader in = null;
        try{
            String path = "C:\\Users\\steve_000\\Desktop\\info.txt"; //<--your path goes  here!
            in = new BufferedReader(new FileReader(path));
            String str = in.readLine();
            ArrayList<String> textList = new ArrayList<String>();
            while((str = in.readLine()) != null){
                textList.add(str); //saves each line that is read from the file
            }

            for(String s: textList){
                mytextArea.append(s + "\n"); //prints each line consecutively
            }

        }catch(IOException e){
            System.out.println("Error reading file");
            e.printStackTrace();
        }
    }

    public static void main(String... args){
        javax.swing.SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                runGUI();
            }
        });
    }

    public static void runGUI() {
        TextRead tr = new TextRead();
        JFrame.setDefaultLookAndFeelDecorated(false);
    }
}