开发者

How to add JButton to GridLayout?

开发者 https://www.devze.com 2022-12-29 20:33 出处:网络
If I have code like so: class X extends JFrame { X() { setLayout(new GridLayout(3,3)); JButton b = new JButton(\"A-ha\");

If I have code like so:

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?开发者_开发知识库
}
};


As what I know, you have to fill all the previous cells before. So you need to add 4 components before you can add the center component. Hmm, it could be a better layoutmanager.

What are you trying to do? Maybe BorderLayout is what you are looking for?


You might want to take a look at the GridBag Layout


This centres vertically and horizontally

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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消