adding JButtons to a JPanel which layout is a "GridLayout"
i am developing a GUI , using java Swing libra开发者_运维知识库ry .I want to add some JButtons to a Jpanel which is Using a Gridlayout as its layout , but i have a problem , the panel's size is about the whole size of the monitor , but the JButtons' size can be different , I may add a 3*3 array of Jbuttons to the panel , while I may add a 10 * 10 array to the panel , the problem is that if i add a 3*3 , the jbuttons would be as large as to occupy the whole display , even the JPanel on the top of the current JPanel (which is named options ), what should i do in order to set a constant size for JButtons so their size in not changed even if they are 2 Jbuttons ( which now takes the whole display) ( the setSize function wont work , and I want the layout to be a GridLayout , not null ) , here's some parts of the code :
public class Edit extends JFrame{
public Edit ()
{
width = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
newer = new JButton(new ImageIcon(b)) ;
done = new JButton(new ImageIcon(f)) ;
savior = new JButton(new ImageIcon(d)) ;
undo = new JButton(new ImageIcon(h)) ;
newer.setSize(200, 60);
done.setSize(200, 60);
savior.setSize(200, 60);
undo.setSize(200, 60);
options = new JPanel();
options.setSize(width , 100);
options.setLayout(new GridLayout(1,5,(width- 1000)/6,20)) ;
options.add(newer);
options.add(done);
options.add(savior);
options.add(undo);
options.setBackground(Color.magenta);
options.add(selector);
this.setExtendedState(this.MAXIMIZED_BOTH);
this.setUndecorated(true);
this.setVisible(true);
view = new JPanel();
regions = new JButton[3][3];
view.setSize(width, height - 100) ;
view.setLayout(new GridLayout(3,3));
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
regions[i][j] = new JButton();
regions[i][j].setSize(80,80) ;
view.add(regions[i][j]);
}
editPhase = new JPanel();
editPhase.setLayout(null);
editPhase.add(options,BorderLayout.NORTH);
editPhase.add(view,BorderLayout.SOUTH);
this.add(editPhase);
}
}
thanks in advance .
Here's an implementation using ideas from the comment:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
int gridSize = 3; // try 4 or 5, etc. buttons are always 50x50
JPanel panel = new JPanel(new GridLayout(gridSize, gridSize));
panel.setPreferredSize(new Dimension(500, 500));
for (int i = 0; i < gridSize; i++) {
for (int j = 0; j < gridSize; j++) {
JPanel buttonPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
JButton button = new JButton();
button.setPreferredSize(new Dimension(50, 50));
buttonPanel.add(button, c);
panel.add(buttonPanel);
}
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
}
精彩评论