Reputation: 53119
Box layout seems to be quite suitable for the needs of typical chat layout like the one I've made in InkScape.
I have based the structure like this:
MainFrame
Chat JPanel - BoxLayout.Y_AXIS
Message list - ScrollablePanel
the list - BoxLayout.Y_AXIS
Text field - Just a text field
Now the only problem I seem to have is, that in the inital phase, the space is divided 50% to 50% between text field and the message list.
However, if the message area is filled, as you can see in the image above and I try to resize the chat window, everything goes well:
So:
Here is the chat panel:
public class ChatPanel extends JPanel {
private BoxLayout layout;
private TextField input;
private MessageList messages;
public ChatPanel() {
layout = new BoxLayout(this, BoxLayout.Y_AXIS);
setLayout(layout);
//Create message list
messages = new MessageList();
messages.appendTo(this);
//Create text field
input = new TextField();
add(input);
}
public void addMessage(String message) {
messages.addMessage(message);
}
public void appendTo(JFrame frame) {
frame.getContentPane().add(this);
}
}
And here is the messageList:
public class MessageList extends JPanel {
public MessageList() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
}
public void addMessage(String message) {
JLabel lb = new JLabel();
lb.setText(message);
add(lb);
validate();
}
public void appendTo(JPanel frame) {
frame.add(new JScrollPane(this));
}
}
Upvotes: 1
Views: 1706
Reputation: 205775
As shown in How to Use BoxLayout: Specifying Component Sizes, you can override the getXxxSize()
methods in your chosen JTextComponent
subclass.
Upvotes: 1