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);
}
});
}
}上面的代码片段的结果的屏幕截图是:
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短