How do I set the relative position of a button?

Go To StackoverFlow.com

0

Now I have a panel called panel1, and I would like to place a button on panel1, and set the position of the button as (30,30). How can I do this?

I tried this, but seems that it is not the right way:(

     int x = panel1.getX();
     int y = panel2.getY();
     button.setLocation(x+30,y+30);

Thanks a lot, the layout manager seems to be a good choice, but here is my problem, I need to generate many buttons dynamically on the panel, and the button size is also different. So which layout manager shall I use? According to the tutorial, it seems that there is no such layout manager....A key problem is I don't want the buttons to look like they are organized in grid, for example, button1 at (20,20) size 15, and button 2 at (40,70) size 20, button 3 at (150,40) size 5.....

2012-04-05 00:38
by faz
Folks will tell you to use the null layout, but I'm going to say, no, don't do this. The best answer is instead to let the layout managers do the positioning for you. You would gain much by studying the tutorial that covers this subject which you can find here: Laying out Components in a Container - Hovercraft Full Of Eels 2012-04-05 00:43
Also, if you want to give your JPanel a 30 point size border where components can't be added, look into giving the JPanel an EmptyBorder(30, 30, 30, 30) - Hovercraft Full Of Eels 2012-04-05 01:03
When you use null Layout, you have to take care for everything. It leads to more problems, than it solves. For example, your Application will look differently on different LnF and Operating System. Moreover in absolute positioning, you have to use button.setSize(50, 30); or another good alternative over setLocation(...) and setSize(...) is simply the use of setBounds(...)nIcE cOw 2012-04-05 05:04
Thanks a lot, my problem is that I want the buttons to be scattered in the panel, not ordered in grid. Is there any way to do this - faz 2012-04-05 06:13
If scattered randomly, then you may have no choice but to use a null layout. If scattered, but non-randomly, then post a picture(s) of your GUI to get us a better handle on just what you're trying to do - Hovercraft Full Of Eels 2012-04-06 00:18


0

I want the buttons to be scattered in the panel.

It's tempting to use an absolute layout for this, but you'd have to figure out a way to keep the buttons from overlapping or even hiding each other. It may be worth Creating a Custom Layout Manager.

2012-04-05 12:19
by Catalina Island


0

Use the form designer in NetBeans and you can place buttons at arbitrary locations relative to each other in a GUI interface. The builder uses the GroupLayout which you could do manually, but it's not recommended.

2012-04-05 12:23
by Dave
Ads