Java GridBagConstraints的问题

时间:2018-08-11 20:11:33

标签: java swing layout-manager gridbaglayout

Click Here for Image

对于我的个人项目,我想在程序中添加音乐播放器。但是,当我尝试使用GridBagConstraintsLayout使3个按钮(播放,暂停和停止)直接位于标签下时,该布局看起来就像我粘贴的图片一样奇怪。我不想播放按钮太长。我希望所有3个按钮的长度相等,并直接位于标签下。有人可以帮我这个问题,也可以发布代码来帮助我吗?附带的图片已随附,并且还包含了一些代码。

panel = new JPanel(new GridBagLayout());
        add(panel);
        GridBagConstraints c = new GridBagConstraints();
        label1 = new JLabel("This is the MaryLand State Song. After exiting, press enter"); 
        c.gridx = 0;
        c.gridy = 0;

        panel.add(label1,c);
        play = new JButton("Play");
        c.gridx = 0;
        c.gridy = 2;
        c.fill = GridBagConstraints.HORIZONTAL;
        panel.add(play,c);
        pause = new JButton("Pause");
        c.gridx = 1;
        c.gridy = 2;
        c.fill = GridBagConstraints.HORIZONTAL;
        panel.add(pause,c);
        stop = new JButton("Stop");
        c.gridx = 2;
        c.gridy = 2;
        c.fill = GridBagConstraints.HORIZONTAL;
        panel.add(stop,c);

2 个答案:

答案 0 :(得分:0)

  

。我不想播放按钮太长。我希望所有3个按钮的长度相等,并直接位于标签下。

您需要标签具有3个单元格的约束。

阅读How to Use GridBagLayout上Swing教程中的部分。将标签添加到面板时,需要使用gridwidth约束。

  

我希望所有3个按钮的长度相等

GrigBagLayout将以其首选大小显示组件。每个按钮的默认首选大小会因每个按钮的文本而略有不同。

如果您确实希望它们都具有相同的大小,则需要使用GridLayout创建一个面板并将3个按钮添加到该面板中。然后,您将标签和面板添加到GridbagLayout中,因此,您现在在单个列中将只有两个组件,因此您不必担心gridwidth约束。

答案 1 :(得分:-1)

希望这会有所帮助

GridBagLayout lay = new GridBagLayout();
// three columns with same weights
lay.columnWeights = new double[] {1,1,1};
panel = new JPanel(lay);
add(panel);

GridBagConstraints c = new GridBagConstraints();

label1 = new JLabel("This is the MaryLand State Song. After exiting, press enter"); 
c.gridx = 0; c.gridy = 0;
// make label span all next to last columns (cells)
c.gridwidth = GridBagConstraints.REMAINDER;

panel.add(label1,c);

c.gridwidth = GridBagConstraints.BOTH;
c.fill = GridBagConstraints.HORIZONTAL;

play = new JButton("Play");
c.gridx = 0; c.gridy = 1;
panel.add(play,c);
pause = new JButton("Pause");
c.gridx = 1; c.gridy = 1;
panel.add(pause,c);
stop = new JButton("Stop");
c.gridx = 2; c.gridy = 1;
panel.add(stop,c);