vincentes
vincentes

Reputation: 45

How can I create a new line in JTextField to type in?

I want to make a Swing program that writes updates on what you have done. It writes all the information on an uneditable JTextField.

For example:

You have changed the text to BLUE.
You have changed the text to RED.

The problem is that I can't make the two lines separate.

What I get is this:

You have changed the text to BLUE. You have changed the text to RED.

What I've tried is this: (This does not work)

TF_BetInfo.setText(TF_BetInfo.getText() + "\nYou have changed the text to BLUE.");
TF_BetInfo.setText(TF_BetInfo.getText() + "\nYou have changed the text to RED.");

Upvotes: 1

Views: 20452

Answers (3)

Antonio Aguilar
Antonio Aguilar

Reputation: 580

You can't actually use several lines in a JTextField, but what you can do, is using a JTextArea of the wanted size, and then use the following:

yourJTextArea.setLineWrap(true);

This will automatically detect when the JTextArea needs to use another line and add it, pretty cool, useful and you only need one code line to do it.

JTextArea is more flexible but if you really want flexibility read about JTextPane or JEditorPane, you can show URLS, internet pages and everything that comes to your mind.

Upvotes: 0

pbespechnyi
pbespechnyi

Reputation: 2291

You can't use JTextField for this. JTextField is sinle-line edit control. That is why you got all your output in one line.

If you want several lines to be printed in edit use JTextArea. In your case you can use jTextArea.append(string) (note: jTextArea is an object of class JTextArea, and string is an object of class String).

Upvotes: 3

vlatkozelka
vlatkozelka

Reputation: 999

you can't have multiple lines with JTextField , you can use JTextArea for that purpose , and the code wouldn't be much different too , you can still use the same code or you can just

TF_BetInfo.append("\nyou have ...... ");

where TF_Betinfo is a JTextArea rather than a JTextField .

Upvotes: 5

Related Questions