George
George

Reputation: 94

how to make word wrap on JLabel for chat window

I am trying to make chat panel, where message texts are shown by JLabel, I want tu make word wrap in it, i have inserted <html>...</html> in a label and sat preferredSize, after that, when i add many messages, scroll not works properly, there appears a lot of free space after text when i scroll down, as shown on this screenshot

http://s10.postimg.org/5pl2w2tbd/Screenshot_5.png

can u tell me better way to do this ?

final class ChatFrame extends JPanel {
        JLabel text;
        JScrollPane scroll = new JScrollPane();
        public ChatFrame(int width,int height) {
            scroll.setPreferredSize(new Dimension(width, height));
            scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
            scroll.getViewport().add(this);
            setBorder(new EmptyBorder(5, 5, 5, 5));
            addMessage("<i>Connecting...</i>", false);
        }
        public void addMessage(String message, boolean right) {
            text = new JLabel("<html>"+message+"</html>");
            text.setOpaque(true);
            text.setBackground(Color.lightGray);
            text.setBorder(new EmptyBorder(5, 5, 5, 5));
            add(text);
            JSeparator sep = new JSeparator(JSeparator.HORIZONTAL);
            sep.setMaximumSize(new Dimension(0, 3));
            add(sep);
            revalidate();
        }
        public Component getChatView() {
            return scroll;
        }
    }

Upvotes: 3

Views: 569

Answers (2)

Anto
Anto

Reputation: 4305

You can use labelUI from the MultiLineLabelUI class (available here) that can be passed to the setUI() method:

text = new JLabel(message);
text.setUI(MultiLineLabelUI.labelUI);

Upvotes: 2

Sergiy Medvynskyy
Sergiy Medvynskyy

Reputation: 11327

Use a non-editable or disabled JTextArea without border.

JTextArea area = new JTextArea();
area.setColumns(50);
area.setWrapStyleWord(true);
area.setEditable(false);
area.setBorder(null);
panel.add(new JScrollPane(area)); // probably without scroll pane if all messages are short

It looks like a label and has one additional advantage: user can copy text from the area.

Upvotes: 8

Related Questions