tags:

views:

80

answers:

3

I have two panels:

  • main_panel
  • child_panel

The main_panel layout is set using:

main_panel.setLayout(flowlayout)

I then added child_panel to main_panel:

main_panel.add(child_panel)

The child_panel gets added to main_panel but its position is at the cross-section of horizontal midpoint and top vertical section of screen. I want child_panel to be at the top left corner, something I could have done by using child_panel.setlocation(a,b) method, if I have set the layout of main_panel as null.

I have used FlowLayout here because I want components in the JPanel to keep adjusting with the size of JFrame.

So can I add child_panel to main_panel at the exact location I want, even if I set the Layout of main_panel as not null?

+1  A: 

How about this?

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test {
    public static void main(String[] args) {
        JFrame f = new JFrame("Test");
        JPanel main = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JPanel child = new JPanel();
        child.add(new JLabel("Label"));
        main.add(child);
        f.getContentPane().add(main);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

}
Savvas Dalkitsis
+1  A: 

I would recommend using GridPanelLayout for your case - you can set the element to be in grid location (0,0) and set it to fill horizontal and vertical, which will cause it to scale with size. You can then follow the look and feel guidelines to get the proper margins and the like.

aperkins
A: 

In this case I would use SpringLayout, it gives you the ability to exactly place the sides of your panel (NORTH, SOUTH, WEST, EAST) with the sides of any other component (in your case the main panel)

This tutorial would clarify what I am saying

Doola