Lets say I have a space of 600px by 900px and I have a method that packs buttons to fit equally into that space with margins. This method would take an int and would shrink or grow the button size based on the number of buttons. How would I even start to make this method?
Asked
Active
Viewed 128 times
0
-
`GridLayout`, `WrapLayout` or write your own layout manager – MadProgrammer Oct 07 '15 at 01:40
-
Also consider a [*sizeVariant*](http://stackoverflow.com/a/17392522/230513) or this [approach](http://stackoverflow.com/a/16014525/230513). – trashgod Oct 07 '15 at 02:01
1 Answers
0
i do not know exactly what you need ,but you may find using Grid layout is what you need , like this sample code below :
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Demo {
public static void main(String[] args) {
JFrame frame=new JFrame();
int rows=2;
int columns=3;
JPanel contentPanel=new JPanel(new GridLayout(rows, columns));
JButton [] myBtns=new JButton[rows*columns];
for(int i=0;i<rows*columns;i++)
{
myBtns[i]=new JButton("btn"+(i+1));
contentPanel.add(myBtns[i]);
}
frame.setContentPane(contentPanel);
frame.setSize(900, 600);
frame.setVisible(true);
}
}

Osama Najjar
- 72
- 4
-
Osama Nijjar, I know it's been a long time but I've been reusing some of this code. I wanted to use this layout and put all the buttons in a JPanel instead of a JFrame. How do I put this on a JPanel? When I try to do "Jpanel.setContentPane(contentPanel)" it doesn't work? How do I achieve this? – Sam Liokumovich Feb 21 '16 at 04:50