Вопрос

I'm a bit confused on how the JTextArea works with regards to newline characters. I've got a JTextArea within a JScrollPane object.

JScrollPane scrollPane4 = new JScrollPane();
scrollPane4.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane4.setBounds(66, 155, 474, 133);
getContentPane().add(scrollPane4);

postingArea = new JTextArea();
postingArea.setMaximumSize(new Dimension(470, 200));
postingArea.setLineWrap(true);
postingArea.setBorder(border);
postingArea.setLineWrap(true);
postingArea.setWrapStyleWord(true);

scrollPane4.setViewportView(postingArea);

The text area is used to gather input from the user and post to an SQL database. The string can be read from the database and redisplayed on a separate web page at another time. When a user enters text, the line does wrap, however, what gets entered into the database is one long string. Therefore, what is redisplayed is one long string with a horizontal scroll bar. Is there a way for me to add newline characters at the appropriate location in the text via an event handler? Or, do I simply inform the user to press "Enter" when they want a new line?

Это было полезно?

Решение 2

I have resolved this by using the Utilities class. In particular, i called getRowEnd () in a loop to determine the logical end of the line (eg. the point of the word wrap) in the JTextArea. I then inserted the string <br> at that point. The updated string was then inserted into an SQL database and later retrieved and displayed on another page. The text displayed correctly with proper line breaks.

Другие советы

I don't see where your TextArea is being added within your ScrollPane. If it were truly being added, the code would have looked like:

JScrollPane scrollPane4 = new JScrollPane(postingArea);

And make your TextArea as:

JTextArea postingArea = new JTextArea(ROWS, COLUMNS); 

Where ROWS and COLUMNS are integers specifying the number of rows and columns in the TextArea.

And don't use setBounds() method, but rely on the LayoutManager to do its work as said by @nachokk. Its not a preference, but good practice. Also, since the LayoutManager will do its work, regardless of you setting your component's bounds, if you LayoutManager doesn't consider the custom bounds parameters, it will calculate it on its own, and that's why you are having the issue.

The rest of your code looks fine.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top