如何将 JButton 添加到 GridLayout?

发布于 2024-09-01 17:50:48 字数 232 浏览 2 评论 0原文

如果我有这样的代码:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

羁拥 2024-09-08 17:50:48

据我所知,您必须先填写所有以前的单元格。所以你需要先添加4个组件,然后才能添加中心组件。嗯,它可能是一个更好的布局管理器。

你想做什么?也许 BorderLayout 就是您正在寻找的?

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?

記柔刀 2024-09-08 17:50:48

您可能想看看 GridBag 布局

You might want to take a look at the GridBag Layout

雪落纷纷 2024-09-08 17:50:48

这垂直和水平居中

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

}

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

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文