Example usage for com.jgoodies.forms.layout FormLayout setConstraints

List of usage examples for com.jgoodies.forms.layout FormLayout setConstraints

Introduction

In this page you can find the example usage for com.jgoodies.forms.layout FormLayout setConstraints.

Prototype

public void setConstraints(Component component, CellConstraints constraints) 

Source Link

Document

Sets the constraints for the specified component in this layout.

Usage

From source file:ai.aitia.meme.utils.FormsUtils.java

License:Open Source License

/**
 * Returns a DefaultFormBuilder containing the specified components and layout.
 * @param cols This parameter corresponds to the <code>encodedColumnSpecs</code> 
 *   parameter of FormLayout's ctor. Besides the encoding defined by FormLayout, 
 *   the following extensions are also available: the characters defined in the 
 *   global <code>{@link #gapLength}</code> variable (hereafter: gap-characters) 
 *   can be used to insert gap-columns. Gap columns must not appear in the 
 *   cell-specification (explained below) and they're automatically included in
 *   column spans. //from  w  w  w  .j ava 2 s . com
 *   Consecutive gap-characters are coalesced into 1 gap column by calculating
 *   their cumulated pixel size.
 * @param rows A string describing general builder settings + cell-specification 
 *   + row/colum spans + row heights + row groups. See the examples. 
 *   The digits and underscores specify which component goes into which cell(s) 
 *   of the layout grid (cell-specification). There can be at most one character 
 *   for every (non-gap) column specified by <code>cols</code>. Rows must be 
 *   separated by the '|' character. Only underscores, digits and letters are 
 *   allowed in the cell-specification (space isn't). Underscore means that a 
 *   cell is empty. A digit/letter character refers to a component in the varargs 
 *   list: '0'..'9', 'A'..'Z', 'a'..'z' (in this order) denote the first 62 
 *   components of the <code>args</code> list. Repeating the same digit specifies
 *   the component's column span (and row span, if repeated in consecutive rows
 *   in the same columns, like '3' in the example).<br> 
 *   After the cell-specification, but before the newline ('|') character
 *   the row height and row grouping can also be specified. It must begin 
 *   with a space to separate it from the cell-specification. The row
 *   height can be a gap-character (for constant heights only) or a string
 *   that is interpreted by RowSpec.decodeSpecs(). If omitted, the height 
 *   spec. of the most recent row is inherited. Content rows inherit the 
 *   height of the previous content row, gap rows inherit the height of 
 *   the previous gap row. A row is a gap row if its cell-specification is
 *   omitted.<br> 
 *   Row grouping forces equal heights to every member of the group. It  
 *   can be specified by "grp?" strings using any character in place of
 *   '?' (except space and '|'. In the example 'grp1' uses '1'). Rows 
 *   using the same grouping character will be in the same group.
 *   By default there're no groups.
 *    <br>
 *   General builder-settings can be specified at the beginning of the 
 *   string, enclosed in square brackets ([..]). (No space is allowed
 *   after the closing ']'). This is intended for future extensions, too. 
 *   The list of available settings is described at the {@link Prop} 
 *   enumeration. Note that setting names are case-sensitive, and should 
 *   be separated by commas.
 * @param args List of components. Besides java.awt.Component objects,
 *   the caller may use plain strings and instances of the {@link Separator}
 *   class. Plain strings are used to create labels (with mnemonic-expansion). 
 *   Separator objects will create and add separators to the form. 
 *   Any of these objects may be followed optionally by a {@link CellConstraints},
 *   a {@link CellConstraints.Alignment} or a {@link CellInsets} object, 
 *   which overrides the cell's default alignment, can extend its row/column 
 *   span and adjust its insets.<br>
 *   If the first element of <code>args</code> is a java.util.Map object,
 *   it is treated as an additional mapping for gap-characters. This 
 *   overrides the default global mapping. Note that gap-characters can 
 *   help you to set up uniform spacing on your forms. For example, if
 *   you use "-" as normal column-gap and "~" as normal row-gap, fine-tuning
 *   the sizes of these gaps later is as easy as changing the mapping for "-"
 *   and "~" &mdash; there's no need to update all the dlu sizes in all layouts.
 * @see   
 *   Example1: <pre>
  *       build("6dlu, p, 6dlu, 50dlu, 6dlu", 
  *                "_0_1_ pref| 6dlu|" + 
 *                "_2_33 pref:grow(0.5) grp1||" +
 *                "_4_33 grp1",
 *                component0, component1, component2, component3,
 *                component4, cellConstraintsForComponent4).getPanel()
 * </pre>
 *   The same exaple with gap-characters: <pre>
  *       build("~ p ~ 50dlu, 6dlu", 
  *                "01_ pref|~|" + 
 *                "233 pref:grow(0.5) grp1||" +
 *                "433 grp1",
 *                component0, component1, component2, component3,
 *                component4, cellConstraintsForComponent4).getPanel()
 * </pre>
 *   Example3 (only the second argument): <pre>
 *       "[LineGapSize=6dlu, ParagraphGapSize=20dlu]_0_1||_2_3||_4_5"
 * </pre>
 *  Note: this method can be used with no components and empty cell-specification,
 *  too. In this case only a {@link DefaultFormBuilder} is created, configured 
 *  and returned. Its operations can then be used to append components to the form.
 */
@SuppressWarnings("unchecked")
public static DefaultFormBuilder build(String cols, String rows, Object... args) {
    Context ctx = new Context();

    // Parse column widths
    //
    int firstArg = 0;
    if (args.length > 0 && args[0] instanceof java.util.Map) {
        ctx.localGapSpec = (java.util.Map<Character, String>) args[0];
        firstArg += 1;
    }
    StringBuilder colstmp = new StringBuilder();
    ctx.contentCol = parseColumnWidths(colstmp, cols, ctx.localGapSpec, 0);

    // Parse the list of components (may include individual cell-constraints)
    //
    ctx.components = new ArrayList<Rec>(args.length);
    for (int i = firstArg; i < args.length; ++i) {
        Rec r = new Rec(args[i]);
        if (i + 1 < args.length) {
            if (args[i + 1] instanceof CellConstraints) {
                r.cc = (CellConstraints) args[++i];
                r.useAlignment = true;
            } else if (args[i + 1] instanceof CellConstraints.Alignment) {
                CellConstraints.Alignment a = (CellConstraints.Alignment) args[++i];
                if (a == CellConstraints.BOTTOM || a == CellConstraints.TOP)
                    r.cc = new CellConstraints(1, 1, CellConstraints.DEFAULT, a);
                else if (a == CellConstraints.LEFT || a == CellConstraints.RIGHT)
                    r.cc = new CellConstraints(1, 1, a, CellConstraints.DEFAULT);
                else if (a == CellConstraints.CENTER || a == CellConstraints.FILL)
                    r.cc = new CellConstraints(1, 1, a, a);
                r.useAlignment = (r.cc != null);
            } else if (args[i + 1] instanceof CellInsets) {
                CellInsets ci = ((CellInsets) args[++i]);
                r.cc = ci.cc;
                r.useAlignment = ci.useAlignment;
                r.useInsets = true;
                //}
                //else if (args[i+1] == null) {   // this would allow superfluous 'null' values
                //   i += 1;
            }
        }
        ctx.components.add(r);
    }

    // Parse general settings (but don't apply yet) 
    //
    EnumMap<Prop, Object> props = null;
    int i = rows.indexOf(']');
    if (i >= 0) {
        String defaults = rows.substring(0, i);
        rows = rows.substring(++i);
        i = defaults.indexOf('[');
        ctx.input = defaults.substring(++i);
        props = Prop.parseGeneralSettings(ctx);
    }

    // Parse cell-specification, row heights and row groups
    //
    String cells[] = rows.split("\\|", -1);
    StringBuilder rowstmp = new StringBuilder();
    java.util.HashMap<Character, int[]> rowGroups = new HashMap<Character, int[]>();
    String lastContentRowHeight = "p", lastGapRowHeight = null;
    int rowcnt = 0;
    for (i = 0; i < cells.length; ++i) {
        rowcnt += 1;
        // See if it begins with a gap-character
        String g = (cells[i].length() > 0) ? getGap(cells[i].charAt(0), ctx.localGapSpec) : null;
        if (g != null)
            cells[i] = ' ' + cells[i];
        int j = cells[i].indexOf(' ');
        boolean gapRow = (j == 0) || (cells[i].length() == 0);
        String rh = null;
        if (j >= 0) {
            String tmp[] = cells[i].substring(j + 1).split("\\s"); // expect height and grouping specifications 
            cells[i] = cells[i].substring(0, j);
            ArrayList<String> gaps = new ArrayList<String>();
            for (j = 0; j < tmp.length; ++j) {
                if (tmp[j].length() == 0)
                    continue;
                if (tmp[j].length() == 4 && tmp[j].toLowerCase().startsWith("grp")) {
                    Character groupch = tmp[j].charAt(3);
                    rowGroups.put(groupch, appendIntArray(rowGroups.get(groupch), rowcnt));
                } else {
                    rh = tmp[j];
                    for (int k = 0, n = tmp[j].length(); k < n
                            && addGap(gaps, getGap(tmp[j].charAt(k), ctx.localGapSpec)); ++k)
                        ;
                }
            }
            if (!gaps.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                flushGaps(gaps, sb, false);
                rh = sb.substring(0, sb.length() - 1);
            }
        }
        if (rh == null) {
            if (gapRow && lastGapRowHeight == null) {
                ctx.b = new DefaultFormBuilder(new FormLayout(colstmp.toString(), ""));
                Prop.setBuilder(props, ctx);
                lastGapRowHeight = parseableRowSpec(ctx.b.getLineGapSpec());
            }
            rh = gapRow ? lastGapRowHeight : lastContentRowHeight;
        } else {
            if (gapRow)
                lastGapRowHeight = rh;
            else
                lastContentRowHeight = rh;
        }
        if (i > 0)
            rowstmp.append(',');
        rowstmp.append(rh);
    }

    // Create builder
    //
    FormLayout fml = new FormLayout(colstmp.toString(), rowstmp.toString());
    ctx.b = new DefaultFormBuilder(fml, debuggable());

    // Apply builder settings (e.g. column groups)
    //
    Prop.setBuilder(props, ctx);
    props = null;

    // Set row groups
    //
    if (!rowGroups.isEmpty()) {
        int[][] tmp = new int[rowGroups.size()][]; // ???
        i = 0;
        for (int[] a : rowGroups.values())
            tmp[i++] = a;
        fml.setRowGroups(tmp);
    }
    rowGroups = null;

    JLabel lastLabel = null;
    java.util.HashSet<Character> done = new java.util.HashSet<Character>(ctx.components.size());
    int h = cells.length;
    for (int y = 0; y < cells.length; ++y) {
        int w = cells[y].length();
        int first = -1;
        for (int x = 0; x < w; ++x) {
            char ch = cells[y].charAt(x);
            if (ch == '_' || done.contains(ch))
                continue;
            int idx = intValue(ch);

            Rec rec;
            try {
                rec = ctx.components.get(idx);
            } catch (IndexOutOfBoundsException e) {
                throw new IndexOutOfBoundsException(
                        String.format("build() cells=\"%s\" ch=%c rows=\"%s\"", cells[y], ch, rows));
            }
            CellConstraints cc = (rec.cc == null) ? new CellConstraints() : (CellConstraints) rec.cc.clone();

            int sx = cc.gridWidth, sy = cc.gridHeight; // span x, span y
            while (x + sx < w && cells[y].charAt(x + sx) == ch)
                sx += 1;
            while (y + sy < h && ((x < cells[y + sy].length() && cells[y + sy].charAt(x) == ch)
                    || (cells[y + sy].length() == 0 && y + sy + 1 < h && x < cells[y + sy + 1].length()
                            && cells[y + sy + 1].charAt(x) == ch))) {
                sy += 1;
            }
            int colSpan = ctx.contentCol[x + sx - 1] - ctx.contentCol[x] + 1;
            ctx.b.setBounds(ctx.contentCol[x] + 1, ctx.b.getRow(), colSpan, sy);
            ctx.b.setLeadingColumnOffset(first & ctx.contentCol[x]); // 0 vagy x (itt nem kell a +1)
            first = 0;
            x += (sx - 1);

            Object comp = ctx.components.get(idx).component;
            if (comp instanceof Component) {
                ctx.b.append((Component) comp, colSpan);
                if (comp instanceof JLabel)
                    lastLabel = (JLabel) comp;
                else {
                    if (lastLabel != null)
                        lastLabel.setLabelFor((Component) comp);
                    lastLabel = null;
                }
            } else if (comp instanceof Separator) {
                comp = ctx.b.appendSeparator(comp.toString());
                lastLabel = null;
            } else {
                comp = lastLabel = ctx.b.getComponentFactory().createLabel(comp.toString());
                ctx.b.append(lastLabel, colSpan);
            }
            if (rec.useAlignment || rec.useInsets) {
                CellConstraints cc2 = fml.getConstraints((Component) comp);
                cc2.insets = cc.insets;
                cc2.hAlign = cc.hAlign;
                cc2.vAlign = cc.vAlign;
                fml.setConstraints((Component) comp, cc2);
            }

            done.add(ch);
        }
        lastLabel = null;
        ctx.b.nextLine();
    }
    return ctx.b;
}

From source file:com.intellij.uiDesigner.radComponents.RadFormLayoutManager.java

License:Apache License

@Override
protected void updateConstraints(final RadComponent component) {
    FormLayout layout = (FormLayout) component.getParent().getLayout();
    layout.setConstraints(component.getDelegee(), gridToCellConstraints(component));
    super.updateConstraints(component);
}

From source file:com.t3.client.ui.tokenpanel.InitiativeListCellRenderer.java

License:Open Source License

/**
 * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean,
 *      boolean)//www  .  j a  va 2 s.c  om
 */
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
        boolean cellHasFocus) {

    // Set the background by type
    Token token = null;
    TokenInitiative ti = (TokenInitiative) value;
    if (ti != null)
        token = ti.getToken();
    if (token == null) { // Can happen when deleting a token before all events have propagated
        currentIndicator.setIcon(null);
        name.setText(null);
        name.setIcon(null);
        setBorder(UNSELECTED_BORDER);
        return this;
    } // endif
    backgroundImageLabel = token.isVisible()
            ? token.getType() == Token.Type.NPC ? GraphicsUtil.BLUE_LABEL : GraphicsUtil.GREY_LABEL
            : GraphicsUtil.DARK_GREY_LABEL;
    name.setForeground(Color.BLACK);

    // Show the indicator?
    int currentIndex = panel.getList().getCurrent();
    if (currentIndex >= 0 && ti == panel.getList().getTokenInitiative(currentIndex)) {
        currentIndicator.setIcon(CURRENT_INDICATOR_ICON);
    } else {
        currentIndicator.setIcon(null);
    } // endif

    // Get the name string, add the state if displayed, then get the icon if needed
    boolean initStateSecondLine = panel.isInitStateSecondLine() && panel.isShowInitState();
    String sName = (initStateSecondLine ? "<html>" : "") + ti.getToken().getName();
    if (TabletopTool.getFrame().getInitiativePanel().hasGMPermission() && token.getGMName() != null
            && token.getGMName().trim().length() != 0)
        sName += " (" + token.getGMName().trim() + ")";
    if (panel.isShowInitState() && ti.getState() != null)
        sName += (initStateSecondLine ? "<br>" : " = ") + ti.getState();
    if (initStateSecondLine)
        sName += "</html>";
    Icon icon = null;
    if (panel.isShowTokens()) {
        icon = ti.getDisplayIcon();
        if (icon == null) {
            icon = new InitiativeListIcon(ti);
            ti.setDisplayIcon(icon);
        } // endif
    } // endif
    name.setText(sName);
    name.setIcon(icon);

    // Align it properly
    Alignment alignment = ti.isHolding() ? CellConstraints.RIGHT : CellConstraints.LEFT;
    FormLayout layout = (FormLayout) getLayout();
    layout.setConstraints(name, new CellConstraints(4, 1, alignment, CellConstraints.CENTER));
    if (alignment == CellConstraints.RIGHT) {
        name.setHorizontalTextPosition(SwingConstants.LEFT);
    } else {
        name.setHorizontalTextPosition(SwingConstants.RIGHT);
    } // endif 

    // Selected?
    if (isSelected) {
        setBorder(SELECTED_BORDER);
    } else {
        setBorder(UNSELECTED_BORDER);
    } // endif
    return this;
}

From source file:net.rptools.maptool.client.ui.tokenpanel.InitiativeListCellRenderer.java

License:Open Source License

/**
 * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean,
 *      boolean)/*from   w w w  .  j  a v  a 2  s  .  com*/
 */
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
        boolean cellHasFocus) {

    // Set the background by type
    Token token = null;
    TokenInitiative ti = (TokenInitiative) value;
    if (ti != null)
        token = ti.getToken();
    if (token == null) { // Can happen when deleting a token before all events have propagated
        currentIndicator.setIcon(null);
        name.setText(null);
        name.setIcon(null);
        setBorder(UNSELECTED_BORDER);
        return this;
    } // endif
    backgroundImageLabel = token.isVisible()
            ? token.getType() == Token.Type.NPC ? GraphicsUtil.BLUE_LABEL : GraphicsUtil.GREY_LABEL
            : GraphicsUtil.DARK_GREY_LABEL;
    name.setForeground(Color.BLACK);

    // Show the indicator?
    int currentIndex = panel.getList().getCurrent();
    if (currentIndex >= 0 && ti == panel.getList().getTokenInitiative(currentIndex)) {
        currentIndicator.setIcon(CURRENT_INDICATOR_ICON);
    } else {
        currentIndicator.setIcon(null);
    } // endif

    // Get the name string, add the state if displayed, then get the icon if needed
    boolean initStateSecondLine = panel.isInitStateSecondLine() && panel.isShowInitState();
    String sName = (initStateSecondLine ? "<html>" : "") + ti.getToken().getName();
    if (MapTool.getFrame().getInitiativePanel().hasGMPermission() && token.getGMName() != null
            && token.getGMName().trim().length() != 0)
        sName += " (" + token.getGMName().trim() + ")";
    if (panel.isShowInitState() && ti.getState() != null)
        sName += (initStateSecondLine ? "<br>" : " = ") + ti.getState();
    if (initStateSecondLine)
        sName += "</html>";
    Icon icon = null;
    if (panel.isShowTokens()) {
        icon = ti.getDisplayIcon();
        if (icon == null) {
            icon = new InitiativeListIcon(ti);
            ti.setDisplayIcon(icon);
        } // endif
    } // endif
    name.setText(sName);
    name.setIcon(icon);

    // Align it properly
    Alignment alignment = ti.isHolding() ? CellConstraints.RIGHT : CellConstraints.LEFT;
    FormLayout layout = (FormLayout) getLayout();
    layout.setConstraints(name, new CellConstraints(4, 1, alignment, CellConstraints.CENTER));
    if (alignment == CellConstraints.RIGHT) {
        name.setHorizontalTextPosition(SwingConstants.LEFT);
    } else {
        name.setHorizontalTextPosition(SwingConstants.RIGHT);
    } // endif 

    // Selected?
    if (isSelected) {
        setBorder(SELECTED_BORDER);
    } else {
        setBorder(UNSELECTED_BORDER);
    } // endif
    return this;
}