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 送给学长毕业祝福语简短