Search code examples
javaswingjpaneltablelayoutupdating

Update component position at run time


I'm currently stuck with the following problem:

I need to dynamically update component positioning at run time. I'm making a form editor for an external application. I use wrapper-classes for standard Swing components, currently JPanel and JLabel. Panels are using TableLayout. I'm storing each component position in a field for each component. When something is changed, I need to recursively update all positions. Here is my method for updating positions:

 public void updatePositioning() {
    Component[] comps = getComponents();
    removeAll();
    for (Component comp:comps) {
        System.out.println("Moving component "+comp + " to x="+pos.get(comp).getX() 
                +" to y="+pos.get(comp).getY());   
        c = new TableLayoutConstraints(String.valueOf(pos.get(comp).getX())+","
                +String.valueOf(pos.get(comp).getY()));

        add(comp, c);
        if (comp instanceof EditPanel) ((EditPanel)comp).updatePositioning();
    }
    repaint();
    revalidate(); 
}

I know, it's rough, but it's not working. All the components are seems to belong to 0,0 grid cell. X's and Y's are correct, as I've seen through debugger. Here is how I add components to my panel:

public void addComponent(TableLayouted comp, int x, int y) {
    c = new TableLayoutConstraints(String.valueOf(x)+","+String.valueOf(y));
    add((JComponent) comp, c);
    //saving position of the component
    pos.put((Component) comp, comp.getTablePositon());
    System.out.println("Component "+comp+"added to x="+x+"y="+y);
}

Any suggestions?


Solution

  • Any suggestions?

    JComponent.getTopLevelAncestor().validate()