The following example will show you how to create a single line JTextArea
. A single line means that you cannot insert a new line in the text area. When pressing the enter key it will be replaced by a space.
This can be done by putting a property called filterNewlines
and set its value to Boolean.TRUE
into the document model of the JTextArea
.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class SingleLineTextArea extends JFrame {
private SingleLineTextArea() {
initialize();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new SingleLineTextArea().setVisible(true));
}
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);
// Filter a new line, pressing enter key will be replaced
// with a space instead.
textArea.getDocument().putProperty("filterNewlines",
Boolean.TRUE);
JScrollPane scrollPane = new JScrollPane(textArea);
// Pressing the Save button print out the text area text
// into the console.
JButton button = new JButton("Save");
button.addActionListener(e -> System.out.println(textArea.getText()));
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(button, BorderLayout.SOUTH);
}
}
The screenshot of the result of the code snippet above is:
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023