我在添加到 JPanel 的组件对齐方面遇到问题。我正在开发一个聊天应用程序。应该使用哪种布局才能达到预期的目的。我尝试了所有的布局,但没有得到想要的。大多数问题是在调整窗口大小时发生的。此外,从包含的图像中了解我想要实现的目标。 提前致谢。 在此输入图像描述
最佳答案
我使用 BoxLayout
制作了一个原型(prototype),没有其他原因,只是我很少使用它并且想尝试一下。通常,GridBagLayout
将是我的首选。
编辑:添加了一张图片(感谢垃圾神!)
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++;
}
}
关于java - 水平向JPanel添加一个又一个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25652405/