right now what happens is they sprawl horizontally.
In addition to @tulskiy's and @Andrew Thompson's suggestions, it may be useful to note that the default layout of JPanel
is FlowLayout
, which arranges components in a horizontal row.
Addendum:
change JPanel
's FlowLayout
to BorderLayout
or some other layout?
Choosing a layout is partly a matter of taste, but I'd combine the suggested approaches, as shown in How to Use Tool Bars. Note how ToolBarDemo
extends JPanel
and then invokes the superclass constructor to specify BorderLayout()
:
public class ToolBarDemo extends JPanel implements ActionListener {
...
public ToolBarDemo() {
super(new BorderLayout());
...
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
...
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(sometable, BorderLayout.CENTER);
}
...
}
Absent extension, just use the constructor directly:
JPanel panel = new JPanel(new BorderLayout());
Alternative, use the setLayout()
method inherited by JPanel
.
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());