Get layout constraints for a component in Java Swing

Below is the mock code I was 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); } } 

There is a method in the container

 public void add(Component comp, Object constraints) 

Is there a way by which we can programmatically obtain the constraints we set, for example getConstraints(...) so that we can use it for later use?

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

What do I need to do after

  Object constraintsForNamePanel = 

to get restrictions for namePanel .

I am currently using

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

It works, but the problem is that I am using WindowsBuilder for the user interface, and my user interface is like changing when adding new components to the pane , and I do not want to copy and paste the restrictions.

+6
source share
1 answer

Having received the solution, I had to do the 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); } 
+7
source

Source: https://habr.com/ru/post/951951/


All Articles