When I run the sample code below the width of JTextArea is fixed (100px) while its height is dynamically adjusted as I type some text in it.
So for example I start with this:
--------------------
| some text |
--------------------
and as I type more text the height of JTextArea expands so it fits the content while preserving the width:
--------------------
| some text, some |
| other longer text|
| etc... |
--------------------
How can I double the width of JTextArea?
When I do it by changing preferredSize
the height is not dynamic anymore.
public class TestTextArea extends JFrame {
public static void main(String[] args) {
new TestTextArea().setVisible(true);
}
public TestTextArea() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0,0,800,600);
setContentPane(createPane());
}
protected Container createPane() {
JTextArea textArea = createTextArea();
// ------------------------------------------
// UNCOMMENT TO DOUBLE THE WIDTH OF JTextArea
// Dimension oldPrefSize = textArea.getPreferredSize();
// Dimension newPrefSize = new Dimension(oldPrefSize.width * 2, oldPrefSize.height);
// textArea.setPreferredSize(newPrefSize);
JPanel pane = new JPanel(new FlowLayout());
pane.add(textArea);
return pane;
}
protected JTextArea createTextArea() {
JTextArea textArea = new JTextArea();
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
return textArea;
}
}
Constructs a new TextArea. A default model is set, the initial string is null, and rows/columns are set to 0.
The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. If you need to obtain only one line of input from the user, you should use a text field.
A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component that provides source compatibility with the java. awt. TextArea class where it can reasonably do so.
Use the JTextArea#setColumns
method to adjust the width
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With