0

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!

Matthieu
  • 2,736
  • 4
  • 57
  • 87
mopr mopr
  • 193
  • 2
  • 4
  • 13

2 Answers2

4

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);
martinez314
  • 12,162
  • 5
  • 36
  • 63
1

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.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • i can't.. cuz later there will many action to add and remove many of jlabel.. so it will more complicated if i do that way... thanks a lot for correcting.. – mopr mopr Oct 31 '12 at 21:44