Dumas45 Dumas45 - 1 year ago 116
Java Question

Adding panel with without layout to the NORTH of BorderLayout


I'm trying to construct simple GUI in Java, where JFrame has Border Layout. I want to put JScrollPane with JTable to CENTER, and JPanel without layout to NORTH.

The problem is that JPanel doesn't visible. There is simple examle of the problem:

JFrame frame = new JFrame("Test frame");

JButton button = new JButton("Test button");
button.setBounds(10, 10, 40, 20);

JPanel panelN = new JPanel(null); // layout = null, panelN without layout
frame.add(panelN, BorderLayout.NORTH);

JTable table = new JTable(new DefaultTableModel(4, 4));
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);

frame.setSize(400, 400);

Answer Source

You have to use a LayoutManager. It's totally discouraged not using layoutManager, but if you want this you have to set panel.setBounds(..) to the panel too.

By default JPanel has FlowLayout so if you put

JPanel panelN = new JPanel(); // FlowLayout used 
frame.add(panelN, BorderLayout.NORTH);

So your frame will look like this.


Layout Managers determines the size and position of the components within a container. Although components can provide size and alignment hints, a container's layout manager has the final say on the size and position of the components within the container.

It's strongly recommended cause for example if you have to resizes components or show in differentes resolutions you delegate this work to layout managers

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download