您好我怎样才能使JTextArea(log)充当日志并显示输入和输出的文本?
这是我到目前为止所拥有的。
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String mess = message.getText();
System.out.println(mess);
}
以下是vars
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextArea log;
private javax.swing.JTextField message;
// End of variables declaration
提前感谢您的帮助!
答案 0 :(得分:5)
append()
会将数据追加到最后。
相反,您需要首先使用getText()
获取文本,将日志连接到它,然后将setText()
与新形成的错误消息一起使用。
因此,从概念上讲,您的新文字是:
错误日志+以前显示的文本
SSCCE
package stack;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class AppendMyError {
public static void main(String[] args) {
final String[] errorMsg = {"NullPointerException",
"ArrayIndexOutOfBoundsException",
"OutOfMemoryException"
};
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
final JFrame jFrame = new JFrame("Useless Title");
final JButton errorBtn = new JButton("Click");
final JTextArea errorLog = new JTextArea(30,30);
final JScrollPane scroll = new JScrollPane(errorLog);
final Random rand = new Random();
jFrame.setLayout(new FlowLayout(FlowLayout.CENTER));
jFrame.getContentPane().add(scroll);
jFrame.getContentPane().add(errorBtn);
jFrame.pack();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setVisible(true);
errorBtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event) {
String currentText = errorLog.getText();
String newError = new Date() + " " + errorMsg[rand.nextInt(errorMsg.length)];
String newTextToAppend = newError + "\n" + currentText;
errorLog.setText(newTextToAppend);
}
});
}
});
}
}
<强>输出:强>
如果您查看时间,较新的消息就在顶部。
答案 1 :(得分:3)
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String mess = message.getText();
System.out.println(mess);
log.append(mess);
}
append()
function将给定文本追加到文档的末尾。
答案 2 :(得分:1)
JTextArea有append(String str)
方法,请尝试:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String mess = message.getText();
System.out.println(mess);
log.append(mess);
}