将JButtons添加到JPanel,其布局是“GridLayout”

时间:2011-07-06 17:53:38

标签: java swing layout jpanel jbutton

我正在使用java Swing库开发GUI。我想将一些JButton添加到Jpanel,它使用Gridlayout作为其布局,但我有一个问题,面板的大小大约是显示器的整个大小,但是JButtons的大小可能会有所不同,我可能会在面板上添加一个3 * 3的Jbuttons数组,而我可能会在面板上添加一个10 * 10的数组,问题是如果我添加一个3 * 3的jbuttons就像占用整个显示器一样大,甚至是当前JPanel顶部的JPanel(也就是命名选项),我该怎么做才能为JButton设置一个恒定的大小,所以即使它们的大小也不会改变是2个Jbuttons(现在占用整个显示)(setSize函数不起作用,我希望布局是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);
    }
}

提前感谢。

1 个答案:

答案 0 :(得分:4)

以下是使用评论中的想法的实现:

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);
  }
}