Something strange occured. I have a text area and a button. When I type text into the area, the button starts moving! Please see attached code. I tried adding more layers of panels and setting component alignments, but it still happens.
class MyFrame extends JFrame {
...
public MyFrame() {
super("example");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
add(panel);
JTextArea _textArea = new JTextArea();
_textArea.setSize(800, 600);
panel.add(_textArea);
JButton btn = new JButton("Send");
panel.add(btn);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000, 800);
setVisible(true);
}
}
whats the mystery all about? how does one component affects the other?
BoxLayout
is a lot more complicated than BorderLayout
, which is what you need. BorderLayout uses general directions like NORTH
, EAST
, SOUTH
, and WEST
, which is very simple. Here's the easy way to get what you're looking for:
class MyFrame extends JFrame {
//...
public MyFrame() {
super("Example");
JTextArea textArea = new JTextArea();
textArea.setSize(800, 600);
add(textArea, BorderLayout.CENTER);
JButton btn = new JButton("Send");
add(btn, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000, 800);
setVisible(true);
}
}
A lot shorter too.