[英]adding JButtons to a JPanel which layout is a “GridLayout”
我正在开发一个 GUI,使用 java Swing 库。我想将一些 JButtons 添加到使用 Gridlayout 作为其布局的 Jpanel 中,但是我有一个问题,面板的大小大约是显示器的整个大小,但是 JButtons ' 大小可以不同,我可以在面板上添加一个 3*3 的 Jbuttons 数组,而我可以在面板上添加一个 10 * 10 的数组,问题是如果我添加一个 3*3,jbuttons 将是大到占据整个显示器,甚至是当前 JPanel 顶部的 JPanel(名为 options ),我应该怎么做才能为 JButtons 设置一个恒定的大小,这样即使它们是 2 个 JButtons,它们的大小也不会改变(现在占据整个显示)( setSize function 不起作用,我希望布局是 GridLayout,而不是 null ),这是代码的一些部分:
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);
}
}
提前致谢。
这是使用评论中的想法的实现:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.