Hello friends,
I am currently developing a chat application and I am having a small problem.

When the user send a message, the message appears in a text area, like in MSN and when the user receives a message the message again appears in the text area, its just a history. Hope you get my point.

The problem is that, when dealing with long messages. The horizontal scroll bar appears and I don't want that.

I just want the long message to stop at the end of the text area and continue on a new line. I don't want to see the horizontal scrollbar. I am using Netbeans.


Thanks in advance for any solution.

Dani AI

Generated

The symptoms described by —long chat lines forcing a horizontal scrollbar—have two common fixes mentioned by others here: manual line breaks (as suggested) or using the text component's built‑in wrapping (as hinted). Letting the component handle wrapping is usually cleaner: it preserves caret/selection behavior and avoids string mangling that can break formatting or timestamps.

A concise approach is to enable line wrapping on the text component and host it in a scroll pane that never shows a horizontal bar. Word-wrapping gives better readability by avoiding mid-word breaks; very long unbroken tokens (URLs, long hashes) either require character-wrapping or explicit soft-breaks added before display. For styled messages, prefer a text pane (StyledDocument or HTML editor kit) instead of plain text to retain formatting while still controlling wrap behavior.

Example setup:

JTextArea chat = new JTextArea();
chat.setLineWrap(true);
JScrollPane sp = new JScrollPane(chat, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

If the scrollbar still appears, confirm the text area is the scroll pane viewport view, check layout constraints so the area can shrink/wrap, and revalidate/repaint after changes. See the Swing text-area tutorial and the JScrollPane API for exact properties and behaviors: How to Use Text Areas and JScrollPane API.

Recommended Answers

All 3 Replies

you could check the number of characters in the string, break it up into sections using a String ArrayList, and insert a \n after each string portion

Thanks for the answer, nice idea, i didn't think about that. But don't you think there is a built in function or something else to do the same thing. I want to optimize my code as far as possible.

Thanks Thanks Buddy ;).

I've never actually used it, but I think this should work.

When you are initializing the JTextArea add this line of code, but change chatArea to whatever variable you are using for your JTextArea.

chatArea.setWrapStyleWord(true);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.