我正在尝试制作聊天面板,其中消息文本由JLabel显示,我想要在其中进行自动换行,我已经在标签中插入了<html> ... </ html>并且坐在preferredSize之后,之后,当我添加很多消息,滚动不正常,当我向下滚动时,文本后出现很多可用空间,如此截图所示
你能告诉我更好的方法吗?
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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用不带边框的不可编辑或禁用的JTextArea.
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
Run Code Online (Sandbox Code Playgroud)
它看起来像一个标签,还有一个额外的好处:用户可以从该区域复制文本.