-1

There are some layouts, like FlowLayout, which maintain the order of components in the order of addition.

Is it possible to permutate some components after addition was made? or the only way is to clear all components and add them again in new order?

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385
  • 1
    Whatg exactly layout manager you need? Actually it depends on the layout you shoose. E.g. GridbagLayout uses constraints and the order doesn't matter – StanislavL Jun 04 '14 at 08:11
  • 1
    Don't _replace_ components; _update_ the component's content in place, for [example](http://stackoverflow.com/q/23978887/230513). – trashgod Jun 04 '14 at 08:12

1 Answers1

3

You can achieve it easily using JPanel#add(component,index) and JPanel#remove(index)

No need to remove all the component form the container. Simply remove the desired component and add new component at the desired position.

Sample code:

final JPanel panel = new JPanel(new FlowLayout());
for (int i = 0; i < 10; i++) {
    panel.add(new JButton(String.valueOf(i)));
}

JButton remove = new JButton("Remove");
remove.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        panel.remove(2);
        panel.revalidate();
    }
});

JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        panel.add(new JButton("21"), 2);
        panel.revalidate();
    }
});
Braj
  • 46,415
  • 5
  • 60
  • 76
  • You might also consider [`Continer#setComponentZOrder`](http://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#setComponentZOrder(java.awt.Component,%20int)) – MadProgrammer Jun 04 '14 at 08:20
  • Thanks I'll read more about it. but will it work in FlowLayout where components are added in sequence. – Braj Jun 04 '14 at 08:22
  • and by using repaint() lets all notifiers are completed, never seen complete explanations, and/but I can't give an answer for why reason(s) too – mKorbel Jun 04 '14 at 08:23
  • @Braj Based on the fact that (most) layout managers layout components in z-order preference, should does ;) – MadProgrammer Jun 04 '14 at 08:24