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.
The setLayout(...) method allows you to set the layout of the container, often a JPanel, to say FlowLayout, BorderLayout, GridLayout, null layout, or whatever layout desired. The layout manager helps lay out the components held by this container.
Try something like this: GridBagLayout gbl=new GridBagLayout(); setLayout(gbl); GridBagConstraints gbc=new GridBagConstraints(); gbc. insets = new Insets(10, 10, 10, 10); JLabel jl = new JLabel("This is a JLabel!", SwingConstants. CENTER); jl.
The FlowLayout is the default layout. It layout the components in a directional flow. The GridLayout manages the components in the form of a rectangular grid. This is the most flexible layout manager class.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With