Java如何创建单行JTextArea?
以下示例将向您展示如何创建单行JTextArea。单行表示您不能在文本区域中插入新行。当按下回车键时,它将被一个空格代替。
这可以通过将名为的属性filterNewlines并将其值设置Boolean.TRUE为的文档模型来完成JTextArea。
package org.nhooo.example.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SingleLineTextArea extends JFrame {
private SingleLineTextArea() {
initialize();
}
private void initialize() {
setSize(500, 200);
setTitle("Single Line Text Area");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
final JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
//过滤新行,按回车键将被替换
//用空格代替。
textArea.getDocument().putProperty("filterNewlines",
Boolean.TRUE);
JScrollPane scrollPane = new JScrollPane(textArea);
//按下保存按钮,打印出文本区域的文本
//进入控制台。
JButton button = new JButton("Save");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(textArea.getText());
}
});
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(button, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SingleLineTextArea().setVisible(true);
}
});
}
}上面的代码片段的结果的屏幕截图是:
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬