how to add component in box layout on north of other and make them all anchor on south?

元气小坏坏 提交于 2019-12-13 02:57:50

问题


I try to make a very mini game.

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)

The view result will be like this:


1

2

3


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

Here is the view result:


1

2

3

neww


but I need something like this:


neww

1

2

3


how should I do?

Is it possible to handle it with BoxLayout?

Here is what I have tried:

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!


回答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);



回答2:


You could add another JPanel in the BorderLayout.NORTH position and add to that panel instead. You can use a BoxLayout for that panel also.

Note, no need to set the layout for your JFrame, as BorderLayout is the default layout for this container. Also, no point setting the preferred size of the panel as the BorderLayout will disregard this.



来源:https://stackoverflow.com/questions/13167669/how-to-add-component-in-box-layout-on-north-of-other-and-make-them-all-anchor-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!