如何在其他北部的盒子布局中添加组件并使它们全部锚定在南部? [英] how to add component in box layout on north of other and make them all anchor on south?

查看:170
本文介绍了如何在其他北部的盒子布局中添加组件并使它们全部锚定在南部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个非常迷你的游戏.

I try to make a very mini game.

我有一个JPanel,它使用的BoxLayout.Y_AXIS包含三个JLabel(JLabels的名称= 1,2,3) 我需要在面板内部固定一个组件以固定在南方(所以我要用胶水)

I have one JPanel, it uses a BoxLayout.Y_AXIS that contains three JLabel (name of JLabels = 1,2,3) I need a component inside that panel to anchor on South (so I use glue)

查看结果将如下所示:

1

2

3

然后我有一个JButton. 如果用户单击该按钮,则JPanel会添加一个新的JLabel(JLabel的名称= neww)

Then I have a JButton. If the user clicks the button, that JPanel adds a new JLabel (name of JLabel = neww)

以下是查看结果:

1

2

3

neww

但是我需要这样的东西:

but I need something like this:

neww

1

2

3

我应该怎么办?

可以用BoxLayout处理吗?

这是我尝试过的:

public class help extends JFrame implements ActionListener{
JPanel panel = new JPanel();
JButton insert = new JButton("insert");
JLabel a = new JLabel("1");
JLabel b = new JLabel("2");
JLabel c = new JLabel("3");
public help()  {
    setSize(300, 200);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(panel, BorderLayout.CENTER);
    panel.setPreferredSize(new Dimension(250,150));
    getContentPane().add(insert, BorderLayout.SOUTH);
    insert.setPreferredSize(new Dimension(50,50));
    insert.addActionListener(this);
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.add(Box.createVerticalGlue());
    panel.add(a);
    panel.add(b);
    panel.add(c);

    setVisible(true);
}

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

@Override
public void actionPerformed(ActionEvent e) {
    panel.add(new JLabel("NEW"));
    panel.revalidate();
    panel.repaint();
}

}

非常感谢您提供任何帮助!

Thanks a lot for any kind of help!

推荐答案

有一个使用索引参数的add()方法版本.由于要在胶水之后添加,请使用1.

There is a version of the add() method that uses an index parameter. Since you want to add it after the glue, use 1.

panel.add(new JLabel("NEW"), 1);

这篇关于如何在其他北部的盒子布局中添加组件并使它们全部锚定在南部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆