如何将JButton添加到GridLayout?

时间:2010-05-12 10:06:47

标签: java swing layout grid-layout

如果我有这样的代码:

class X extends JFrame
{
X()
{
setLayout(new GridLayout(3,3));
JButton b = new JButton("A-ha");
/*I would like to add this button in the center of this grid (2,2)*/
//How can I do it?
}
};

3 个答案:

答案 0 :(得分:1)

据我所知,您必须先填写之前的所有单元格。因此,在添加中心组件之前,需要添加4个组件。嗯,它可能是一个更好的布局管理员。

你想做什么?也许BorderLayout正是您要找的?

答案 1 :(得分:1)

您可能需要查看GridBag Layout

答案 2 :(得分:1)

垂直和水平居中

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class centerbutton extends JFrame{
   public centerbutton(){
      setLayout(new BorderLayout());

      JPanel panel = new JPanel();
      JButton button = new JButton("A-ha!");
      button.setAlignmentX(
      Component.CENTER_ALIGNMENT);
      panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
      panel.add(Box.createVerticalGlue());
      panel.add(button);
      panel.add(Box.createVerticalGlue());

      getContentPane().add(panel);

      setVisible(true);
   }

   public static void main(String[] args) {
      new centerbutton();
   }

}