简体   繁体   中英

Java - Saving each line of text instead of replacing it

everytime I write something in the text box and press enter, I'm able to see the message in the "Uneditabletest", however, if I write something different and press enter, It will replace my last message, what do I do to have them saved one after another? Like if it was a chat or something similar.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Tutorial extends JFrame {

JTextField jtfText1, jtfUneditableText;
String disp = "";
TextHandler handler = null;

public Tutorial() {
    super("TextField Test Demo");
    Container container = getContentPane();
    container.setLayout(new FlowLayout());
    jtfText1 = new JTextField(10);
    jtfUneditableText = new JTextField("Uneditable text field", 20);
    jtfUneditableText.setEditable(false);
    container.add(jtfText1);
    container.add(jtfUneditableText);
    handler = new TextHandler();
    jtfText1.addActionListener(handler);
    jtfUneditableText.addActionListener(handler);
    setSize(325, 100);
    setVisible(true);
}

private class TextHandler implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jtfText1) {
            disp = "text1 : " + e.getActionCommand();
        } else if (e.getSource() == jtfUneditableText) {
            disp = "text3 : " + e.getActionCommand();
        }

        jtfUneditableText.setText(disp);

        }
    }

    public static void main(String args[]) {
        Tutorial test = new Tutorial();
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Simply append it to the end. In this case, it would be jtfUneditableText.setText(jtfUneditableText.getText() + "\\n" + disp)

There should be something like getText() in jtfUneditableText, so you can do jtfUneditableText.setText(jtfUneditableText.getText() + "\\n" + disp);

So the text in jtfUneditableText will be what was there before (jtfUneditableText.getText()) plus a line break (\\n), and the new text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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