简体   繁体   English

如何保存JTextArea文本?

[英]how to save JTextArea text?

I would like to know how to save JTextArea text that when user types something in area it stays there even when user exits the program and re-opens it. 我想知道如何保存JTextArea文本,当用户在区域中键入某些内容时,即使用户退出程序并重新打开它,它也会停留在该文本中。

Sorry for my bad english and grammar. 对不起,我的英语和语法不好。

There are multiple ways to do this. 有多种方法可以做到这一点。

  1. Use a database: You can store many different inputs in the database, and link it to the user who made the input, or anything else. 使用数据库:您可以在数据库中存储许多不同的输入,并将其链接到进行输入的用户或其他任何人。
  2. Write to a .txt file: This allows you to access the data from outside your application very easily. 写入.txt文件:这使您可以非常轻松地从应用程序外部访问数据。
  3. Serialize String: You could save the text in a String and serialize the Object. 序列化字符串:您可以将文本保存在字符串中并序列化对象。

There are many ways to do it, hard to determine which is the best, as we do not know what you want to achieve. 有很多方法可以做到,很难确定哪种方法最好,因为我们不知道您要实现什么目标。

In general, you probably want to use Swing components to expose fields in some "model" object, and save the model (to a database, file, etc.) only on explicit user action, but also save it to some user-private place on every user action ("auto-save"). 通常,您可能希望使用Swing组件来公开某些“模型”对象中的字段,并仅在显式用户操作时将模型保存(保存到数据库,文件等),还要将其保存到某些用户专用的地方每个用户的操作(“自动保存”)。 However, java.util.prefs.Preferences may be useful for exactly what you're asking. 但是, java.util.prefs.Preferences可能对您所要的内容很有用。 A simple example (untested): 一个简单的例子(未经测试):

public class SwingPrefsDemo extends JFrame {
  // other fields, etc...
  Preferences prefsNode = Preferences.userNodeForPackage(SwingPrefsDemo.class);
  JTextField tf_ta;

  public SwingPrefsDemo() {
    // ...
    tf_ta = new JTextArea();
    tf_ta.setText(prefsNode.get("tf_ta","enter text here"));
    this.add(tf_ta);
    tf_ta.getDocument().addDocumentListener(new DocumentListener() {
      public void changedUpdate(DocumentEvent evt) { change(); }
      public void insertUpdate(DocumentEvent evt) { change(); }
      public void removeUpdate(DocumentEvent evt) { change(); }
      private void change() {
        prefsNode.put("tf_ta",tf_ta.getText());
      }});
  } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM