mopr mopr
mopr mopr

Reputation: 193

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

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!

Upvotes: 0

Views: 3752

Answers (2)

Reimeus
Reimeus

Reputation: 159784

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.

Upvotes: 1

martinez314
martinez314

Reputation: 12332

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

Upvotes: 4

Related Questions