我有一个程序,正在尝试测试是否创建了文件(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

最佳答案

因此,根据可用的代码,您只需在创建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被设计为使用布局管理器,并且许多更新接口的功能都与之相关。如果您放弃了布局管理器,请准备好永不停止的工作和挫败感

10-04 14:11