Tomáš Zato
Tomáš Zato

Reputation: 53119

Chat layout with BoxLayout manager

Box layout seems to be quite suitable for the needs of typical chat layout like the one I've made in InkScape.
enter image description here

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.

enter image description here

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:

enter image description here

So:

  1. I want the textarea to keep the same size, even when message container is empty.
  2. There must be a method to be called to simulate me resizing the window so that the panels update properly.

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

Answers (1)

trashgod
trashgod

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

Related Questions