Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在BoxLayout中居中的JLabel中居中JButtons?_Java_Swing_Layout_Jlabel_Boxlayout - Fatal编程技术网

Java 如何在BoxLayout中居中的JLabel中居中JButtons?

Java 如何在BoxLayout中居中的JLabel中居中JButtons?,java,swing,layout,jlabel,boxlayout,Java,Swing,Layout,Jlabel,Boxlayout,我是Java GUI编程新手,对BoxLayout有一个奇怪的问题: 我有一个带有图标的JLabel。标签上添加了两个jbutton。Jlabel从JFrame放置在BorderLayout的中心位置。现在,我希望这两个jbutton始终位于JLabel的中心,即使我调整JFrame的大小。使用setAlignmentX()时,jbutton水平居中,但对于垂直方向,没有使用setAlignmentY()的解决方案 代码如下: package footballQuestioner; impor

我是Java GUI编程新手,对
BoxLayout
有一个奇怪的问题: 我有一个带有
图标的
JLabel
。标签上添加了两个
jbutton
Jlabel
JFrame
放置在
BorderLayout
中心位置。现在,我希望这两个
jbutton
始终位于
JLabel
的中心,即使我调整
JFrame
的大小。使用
setAlignmentX()
时,jbutton水平居中,但对于垂直方向,没有使用
setAlignmentY()
的解决方案

代码如下:

package footballQuestioner;

import java.awt.BorderLayout;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Houdini {

    public static void main(String[] args) {
        JFrame frame = new House();
    }

    }

    class House extends JFrame {

    private JLabel label = new JLabel(
            new ImageIcon(
                    "C:\\Users\\laudatio\\Documents\\Java\\MyProject\\src\\footballQuestioner\\footballfield.jpg")
            );
    private JButton one=new  JButton("one");
    private JButton two=new JButton("two");


    public House() {


        label.setLayout(new BoxLayout(label, BoxLayout.Y_AXIS));

        label.add(one);
        label.add(two);

        one.setAlignmentX(CENTER_ALIGNMENT);
        one.setAlignmentY(CENTER_ALIGNMENT);
        two.setAlignmentX(CENTER_ALIGNMENT);
        two.setAlignmentY(CENTER_ALIGNMENT);


        setLayout(new BorderLayout());
        setLocation(300, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(true);

        add(label,BorderLayout.CENTER);

        pack();
        setVisible(true);


    }

}
请帮忙-((((

但是对于垂直方向,没有使用setAlignmentY()的解决方案

在两个组件之前和之后使用“胶水”。有关更多信息和示例,请参阅上Swing教程的部分


虽然程序员建议使用
GridBagLayout
是一个更简单的解决方案,但了解“glue”和“struts”有助于定制
BoxLayout

的布局,而使用
GridBagLayout