Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get layout constraints for a component in Java Swing

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.

like image 879
TheKojuEffect Avatar asked Aug 18 '13 03:08

TheKojuEffect


People also ask

What is the use of setLayout () method?

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.

How do you use insets in GridBagLayout?

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.

Which is the default layout in Swing?

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.


1 Answers

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);
    }
like image 127
TheKojuEffect Avatar answered Sep 19 '22 08:09

TheKojuEffect