我应该使用什么布局管理器

问题描述 投票:0回答:1

我正在用Java聊天,需要在JPanel中显示旧消息。我需要一个图像和正在发送/接收的消息才能显示,每个图像都在自己的行上。我目前拥有的代码:

JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel container = new JPanel();
container.setPreferredSize(new Dimension(300, 400));

// Printing five messages
for (int i = 0; i < 5; i++) {
    JPanel p = new JPanel();
    p.setPreferredSize(new Dimension(300, 40));
    p.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));

    JLabel img = new JLabel("Image : ");
    JLabel txt = new JLabel("This is some text");

    p.add(img);
    p.add(txt);

    img.setAlignmentX(Component.LEFT_ALIGNMENT);
    txt.setAlignmentX(Component.LEFT_ALIGNMENT);

    container.add(p);
}

f.add(container);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true); 

结果:enter image description here

现在,我指定的是每条消息的宽度和高度,这不太好,因为它应该自动调整其内容的大小。我觉得应该为此提供一个不错的布局管理器,但是我是新手,因此很感谢我的帮助,因为我不知道该使用哪个。

java swing awt
1个回答
0
投票

它应该自动调整大小为其内容。

这里有换行符是主要问题。

一种方法可能是:

  1. 使用垂直框
  2. 将文本换成HTML

类似:

import java.awt.*;
import javax.swing.*;

public class Chat extends JPanel
{
    private Box messageBox = Box.createVerticalBox();

    public Chat()
    {
        setLayout( new BorderLayout() );
        add(messageBox, BorderLayout.PAGE_START);

        addMessage("Short message");
        addMessage("A longer message that should wrap as reqired onto another line. This should happen dynamically");
    }

    public void addMessage(String text)
    {
        JPanel messagePanel = new JPanel( new BorderLayout() );

        JLabel label = new JLabel( new ImageIcon("about16.gif") );
        messagePanel.add(label, BorderLayout.LINE_START);

        JLabel message = new JLabel("<html>" + text + "</html>");
        messagePanel.add(message);

        messageBox.add(messagePanel);
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Chat");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new Chat());
        frame.pack();
        frame.setSize(200, 100);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args) throws Exception
    {
        java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.