Frage

Below is a mock up of code that I've been working on.



public class Pane {

    private final JPanel pane;
    private JPanel namePanel;
    private final JTextField panIdField;

    public Pane() {
        pane = new JPanel();
        pane.setLayout(new MigLayout("", "[][grow]", "[][][][][]"));

        namePanel = new JPanel();
        pane.add(namePanel, "cell 1 1,growx");

        panIdField = new JTextField();
        pane.add(panIdField, "cell 1 2,growx");
        panIdField.setColumns(10);

    }

    public void replaceNameField(JPanel newNamePanel) {
        this.namePanel = newNamePanel;
        // Object constraintsForNamePanel = 
        pane.remove(namePanel);
        pane.add(newNamePanel, constraintsForNamePanel);
    }

}

In Container there's method

public void add(Component comp, Object constraints)

Is there any way that we can programatically get the constraints that we set, like getConstraints(...) so that we can use it for later use?

In my code, I want to use it to replace a old component with a new one at the same place.

What do I have to do after

 Object constraintsForNamePanel = 

to get the constraints for namePanel.

Currently, I'm using

pane.add(newNamePanel, "cell 1 1,growx");

It is working but the problem is I'm using WindowsBuilder for UI and my UI is like to change when I add new components to the pane and I don't want to copy and paste the constraints.

War es hilfreich?

Lösung

Got the solution, I had to do following.


public void replaceNameField(JPanel newNamePanel) {
     MigLayout layout = (MigLayout) pane.getLayout();
     Object constraintsForNamePanel = layout.getComponentConstraints(this.namePanel);
     pane.remove(this.namePanel);

      this.namePanel = newNamePanel;
      pane.add(newNamePanel, constraintsForNamePanel);
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top