Search code examples
javaswinglayoutalignmentmiglayout

MigLayout alignment of elements


enter image description here

the code that i have:

the JPANEL

JPanel dadosdaparte = new JPanel(new MigLayout("fillx"));

adding to JPANEL

        dadosdaparte.setBorder(BorderFactory.createTitledBorder("Dados da Parte"));
        dadosdaparte.add(lblnomedaparte, "span, split 2");
        dadosdaparte.add(tfnomedaparte, "growx, wrap");
        dadosdaparte.add(lblnacionalidade, "split 7");
        dadosdaparte.add(cboxNacionalidade);
        adicionaNacionalidades();
        dadosdaparte.add(lblcirg);
        dadosdaparte.add(tfcirg);
        dadosdaparte.add(lblcpfcnpj);
        dadosdaparte.add(tfcpfcnpj);
        dadosdaparte.add(cpfcnpjinvalido, "wrap");

the miglayout cheat sheet or help, i just saw the positioning of the cell, not the alignment of the itens inside the cell, if someone can help me, i appreciate


Solution

  • As stated in MiG Layout Quick Start Guide:

    Components that are alone in a cell can be aligned within that cell, if there is space left over. You can specify this in the column/row constraints to get a default align for the components and/or you can specify it in the component's constraints.

    For instance, the following code:

    JPanel panel = new JPanel(new MigLayout("fillx"));
    panel.add(new JLabel("Very long label:"), "");
    panel.add(new JTextField(20), "wrap");
    panel.add(new JLabel("Short 1:"), "right");
    panel.add(new JTextField(20));
    panel.add(new JLabel("Short 2:"), "right");
    panel.add(new JTextField(10), "wrap");
    

    Will produce this outcome:

    enter image description here

    You can also define the component's alignment as a column constraint, if you know how many columns you will have. The following will produce the same outcome as previous one:

    JPanel panel = new JPanel(new MigLayout("fillx","[right][][][]"));
    panel.add(new JLabel("Very long label:"), "");
    panel.add(new JTextField(20), "wrap");
    panel.add(new JLabel("Short 1:"), "");
    panel.add(new JTextField(20));
    panel.add(new JLabel("Short 2:"), "");
    panel.add(new JTextField(10), "");