将组件一个接一个地水平添加到JPanel

时间:2014-09-03 19:39:35

标签: java swing layout alignment

enter image description here我遇到了添加到JPanel的组件对齐问题。我正在开发一个聊天应用程序。应该使用哪种布局来实现预期目标。我尝试了所有的布局,但我没有得到满足的要求。大多数问题发生在调整窗口大小时。此外,从包含的图像中了解我想要实现的目标。 提前致谢。 在此处输入图像描述

enter image description here

1 个答案:

答案 0 :(得分:4)

我使用BoxLayout制作了一个原型,除了我很少使用它之外没有其他原因,感觉就像尝试它一样。通常情况下,GridBagLayout将是我的第一选择。

编辑:添加了图片(感谢trashgod!)

enter image description here

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class MessageAppDemo implements Runnable
{
  private String[] messages = new String[] {
      "Hello?",
      "Hey, what's up?",
      "Where are you?",
      "Right behind you.",
      "Stop following me!",
      "But you owe me money.",
      "I'll gladly repay you on Tuesday.",
      "You said that last week!",
      "But now I actually have a job."
  };
  private int msgCounter = 0;
  private JPanel panel;
  private JScrollPane scrollPane;
  private Timer timer;

  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new MessageAppDemo());
  }

  public void run()
  {
    panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

    scrollPane = new JScrollPane(panel);
    scrollPane.setVerticalScrollBarPolicy(
        JScrollPane.VERTICAL_SCROLLBAR_NEVER);
    scrollPane.setAutoscrolls(true);

    JFrame frame = new JFrame("Message App");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    frame.setSize(260, 180);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    timer = new Timer(1500, new ActionListener()
    {
      public void actionPerformed(ActionEvent event)
      {
        if (msgCounter < messages.length)
        {
          addMessage(messages[msgCounter]);
        }
        else
        {
          timer.stop();
        }
      }
    });
    timer.start();
  }

  private void addMessage(String text)
  {
    boolean rightAligned = msgCounter % 2 != 0;
    Color color = rightAligned ? Color.CYAN : Color.ORANGE;

    JLabel label = new JLabel(text);
    label.setOpaque(true);
    label.setBackground(color);
    label.setBorder(BorderFactory.createCompoundBorder(
        BorderFactory.createLineBorder(Color.BLUE),
        BorderFactory.createEmptyBorder(2,4,2,4)
    ));

    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    p.setBorder(BorderFactory.createEmptyBorder(2,4,2,4));

    if (rightAligned)
    {
      p.add(Box.createHorizontalGlue());
      p.add(label);
    }
    else
    {
      p.add(label);
      p.add(Box.createHorizontalGlue());
    }

    panel.add(p);
    panel.revalidate();
    int x = panel.getPreferredSize().width;
    int y = panel.getPreferredSize().height;
    panel.scrollRectToVisible(new Rectangle(x-1 ,y-1, 1, 1));

    msgCounter++;
  }
}