3

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;
        }
    }
George
  • 94
  • 7
  • You'll generally find that the layout manager has a lot to do with this as you can see in [this example](http://stackoverflow.com/questions/14737810/jlabel-show-longer-text-as-multiple-lines/14738193#14738193), which uses a `GridBagLayout` – MadProgrammer Feb 13 '15 at 20:35

2 Answers2

8

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.

Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48
2

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);
Anto
  • 4,265
  • 14
  • 63
  • 113