【问题标题】:What layout manager should I use我应该使用什么布局管理器
【发布时间】:2020-03-21 17:43:12
【问题描述】:

我正在用 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); 

结果:

现在我正在指定每条消息的宽度和高度,这不是很好,因为它应该自动调整大小以适应其内容。我觉得应该有一个很好的布局管理器来解决这个问题,但我是新来的,所以我不知道该使用哪一个,因此非常感谢您的帮助。

【问题讨论】:

  • 您可以使用GridLayout(0, 1)(行数可变,一列),但我自己可能会将其显示为带有自定义渲染器的JList,一个显示图像和文本的渲染器。或者是一个有两列的 JTable:图像和文本
  • 我自己会使用 JEditorPane,但您的要求可能会有所不同。如果您告诉它们,许多 Swing 组件也会解释简单的 HTML,所以"&lt;html&gt;&lt;p&gt;&lt;image/&gt;Some text.&lt;/p&gt;" 也不是不可能的。

标签: java swing awt chat


【解决方案1】:

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

文本换行是这里的主要问题。

一种方法可能是:

  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() );
    }
}

【讨论】:

    猜你喜欢
    • 2015-06-05
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    相关资源
    最近更新 更多