Search code examples
javaswingjinternalframe

Resize makes things wrong


I want to create a JInternalFrame with some components in it.

My aim is to design a bash console in Java.

My frame is made of 4 components:

  • JTextArea included into a JScrollPane
  • JLabel with the text "Cmd:"
  • JTextField
  • JButton with the text "Send"

And I have the following code:

Box box = Box.createHorizontalBox();
box.add(Box.createVerticalStrut(5));
box.add(this.cmd_label);
box.add(Box.createVerticalStrut(5));
box.add(this.cmd_input);
box.add(Box.createVerticalStrut(5));
box.add(this.submit);
box.add(Box.createVerticalStrut(5));

Box mainBox = Box.createVerticalBox();
mainBox.add(Box.createHorizontalStrut(5));
mainBox.add(this.result_scroll);
mainBox.add(Box.createHorizontalStrut(5));
mainBox.add(box);
mainBox.add(Box.createHorizontalStrut(5));
add(mainBox);

So when the frame has not been maximized, I have a correct look:

Non-maximized frame

But when I maximize it, all components are incorrectly located:

Maximized frame

So, here is my question: How can I set a weight to the components to fix their location every time, or, how can I fix it?

Thanks.


Solution

  • I think this would be better done with a BorderLayout. In a BorderLayout, the component specified as the center component will expand to fill as much space as possible, and the other components will remain at their preferred sizes.

    int hgap = 5;
    int vgap = 5;
    internalFrame.getContentPane().setLayout(new BorderLayout(hgap, vgap));
    internalFrame.getContentPane().add(this.result_scroll, BorderLayout.CENTER);
    JPanel bottomPanel = new JPanel();
    bottomPanel.add(this.cmd_label);
    bottomPanel.add(this.cmd_input);
    bottomPanel.add(this.submit);
    internalFrame.getContentPane().add(bottomPanel, BorderLayout.SOUTH);