Java - 保存每行文本而不是替换它
每当我在文本框中写入内容并按下回车键时,我能够在“Uneditabletest”中看到该消息,但是,如果我写入了不同的内容并按下Enter键它会取代我最后的信息,我该如何让他们一个接一个地保存?就好像它是一个聊天或类似的东西。Java - 保存每行文本而不是替换它
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);
}
}
回答:
只需将其追加到最后。在这种情况下,这将是jtfUneditableText.setText(jtfUneditableText.getText() + "\n" + disp)
回答:
应该有类似的getText()在jtfUneditableText,所以你可以做jtfUneditableText.setText(jtfUneditableText.getText() + "\n" + disp);
所以在jtfUneditableText文字会是什么在那里之前(jtfUneditableText.getText())加上换行符(\ n)和新文本。
以上是 Java - 保存每行文本而不是替换它 的全部内容, 来源链接: utcz.com/qa/264492.html