javaswingdomdefaultstyleddocument

Java GUI: Document Object Model


HTML has a Document Object Model, which Javascript can then manipulate / move around.

When I create GUIs in Swing -- the model appears to be very difference (I don't know the name of the model), since I'm creating layout managers, and sticking objects inside of them.

My question: is there someway to manipulate Java GUis in a DOM like manner?

[For example, I want to be able to delete / add nodes, move childs around, etc ...]

Thanks!


Solution

  • For Swing components, everything starts from a set of JFrame's (you can also have JWindow's and JDialog's, but you usually have at least one root frame). Most likely, all you care about is the contentPane of that JFrame (but you could care also about its ownedWindows, etc...).

    So from the JFrame, you can get the content pane as following:

    Container contentPane = frame.getContentPane();
    

    From there, you can start going down the Tree of components, using:

    Component[] children = contentPane.getComponents();
    

    From a child, you can get its parent with:

    Container parent = child.getParent();
    

    To add a component to a container:

    container.add(someComponent);
    container.validate();
    

    To remove a component from a container:

    container.remove(someComponent);
    container.validate();
    

    To move a component from one Container to another, simply remove it from one and add it to the other.

    I am not sure this answers your question. It would be easier if you could post real examples of what you are trying to do.