Reputation: 12899
I have the same problem described here but none of the answer worked out for me.
I have a Panel
with a BoxLayout
with Axis = Y Axes
, because I would like to stack elements one below the other, but I would like to be able to align the elements to the right and to the left, so now I'm inserting to this Panel, other Panels:
arrayList.forEach(message -> {
JLabel label = new JLabel("[" + message.getSender() + " " + message.when() + "] : " + message.message(), SwingConstants.LEFT);
Panel panel = null;
try {
panel = new Panel(new FlowLayout(message.getSender().equals(this.client.getName()) ? FlowLayout.LEFT : FlowLayout.RIGHT));
panel.add(label);
panel.setSize(panel.getSize().width, label.getPreferredSize().height);
panel.setPreferredSize(new Dimension(panel.getSize().width, label.getPreferredSize().height));
label.setBackground(message.getSender().equals(client.getName()) ? Color.GREEN : Color.BLUE);
label.setForeground(message.getSender().equals(client.getName()) ? Color.BLACK : Color.WHITE);
} catch (RemoteException ex) {
ex.printStackTrace();
}
label.setOpaque(true);
chat.add(panel, BorderLayout.PAGE_START);
});
However this is not working since the result is the following:
However the supposed result should be like one message below the other without any kind of space between the messages... what am I missing?
Upvotes: 0
Views: 66
Reputation: 324088
chat.add(panel, BorderLayout.PAGE_START);
That statement doesn't make sense. It implies you are using a BorderLayout, when your question stated you are using a BoxLayout. When using a BoxLayout, you don't specify a constraint.
I have a Panel with a BoxLayout with Axis = Y Axes,
The BoxLayout respects the components maximum size.
So when there is extra space in the parent panel each child panel will grow until all the extra space is used.
Don't play with the size or preferred size methods.
One solution is to use a wrapper panel that respects the preferred height of all the child panels.
So your code should be something like:
Box chat = Box.createVerticalBox();
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(chat, BorderLayout.PAGE_START);
frame.add(wrapper, BorderLayout.CENTER);
Now the "chat" panel height will respect the preferred height of each component added to it.
Upvotes: 3