tags:

views:

227

answers:

3

How can I specify the location on JFrame that a component (JLabel specifically) is placed? I created a JFrame object and added a JLabel and a JList to the frame but both objects are being placed on top of each other. I have tried using

label.setBounds(10,10,10,10);
list.setBounds(20,20,100,100);

and

label.setLocation(10,10);
list.setLocation(10, 50);

Neither of these are working. Any help is appreciated! Thanks.

+1  A: 

Layout Managers will do that for you.

With the default Layout BorderLayout, try

setLayout(new BorderLayout());
getContentPane().add(yourLabel, BorderLayout.NORTH);
getContentPane().add(yourList, BorderLayout.CENTER);
Peter Lang
+2  A: 

In Java, layout managers are used which determine the way the components will be placed. You can find more information about layout managers here: http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html

If you definitely want to use coordinates to put your components, you could try:

JFrame frame = new JFrame();
frame.setLayout(null);

Otherwise, a very good GUI editor for Java is NetBeans which is using the GroupLayout by default.

Alex
Setting the layout manager to null is the preferred way to use absolute positioning when laying out components. however IMO, the GUI Editor for NetBeans is a real pain and I find it easier to not use it.
ChadNC
The NetBeans UI editor is excellent and right now one of the best there is available for free. Learning how the different LayoutManagers work can be difficult, but it will be well worth it in the end.
willcodejavaforfood
A: 

Thank you for getting me going in the right direction. I ended up settings the layout to null so that the default layout manager was removed and then I was able to place object where ever I wanted.

Thanks again!