Example usage for java.awt Component getPreferredSize

List of usage examples for java.awt Component getPreferredSize

Introduction

In this page you can find the example usage for java.awt Component getPreferredSize.

Prototype

public Dimension getPreferredSize() 

Source Link

Document

Gets the preferred size of this component.

Usage

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Calculates and sets the each column to it preferred size.  NOTE: This
 * method also sets the table height to 10 rows.
 * //from   w  w  w  .j  a v a  2 s .c  om
 * @param table the table to fix up
 * @param numRowsHeight the number of rows to make the table height (or null not to set it)
 */
public static void calcColumnWidths(final JTable table, final Integer numRowsHeight, final Integer maxWidth) {
    if (table != null) {
        JTableHeader header = table.getTableHeader();

        TableCellRenderer defaultHeaderRenderer = null;

        if (header != null) {
            defaultHeaderRenderer = header.getDefaultRenderer();
        }

        TableColumnModel columns = table.getColumnModel();
        TableModel data = table.getModel();

        int margin = columns.getColumnMargin(); // only JDK1.3

        int rowCount = data.getRowCount();

        int totalWidth = 0;

        for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
            TableColumn column = columns.getColumn(i);

            int columnIndex = column.getModelIndex();

            int width = -1;

            TableCellRenderer h = column.getHeaderRenderer();

            if (h == null)
                h = defaultHeaderRenderer;

            if (h != null) // Not explicitly impossible
            {
                Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1,
                        i);

                width = c.getPreferredSize().width;
            }

            for (int row = rowCount - 1; row >= 0; --row) {
                TableCellRenderer r = table.getCellRenderer(row, i);

                Component c = r.getTableCellRendererComponent(table, data.getValueAt(row, columnIndex), false,
                        false, row, i);

                width = Math.max(width, c.getPreferredSize().width + 10); // adding an arbitray 10 pixels to make it look nicer

                if (maxWidth != null) {
                    width = Math.min(width, maxWidth);
                }
            }

            if (width >= 0) {
                column.setPreferredWidth(width + margin); // <1.3: without margin
            } else {
                // ???
            }

            totalWidth += column.getPreferredWidth();
        }

        // If you like; This does not make sense for two many columns!
        Dimension size = table.getPreferredScrollableViewportSize();
        //if (totalWidth > size.width)
        {
            if (numRowsHeight != null) {
                size.height = Math.min(size.height, table.getRowHeight() * numRowsHeight);
            }
            size.width = totalWidth;
            table.setPreferredScrollableViewportSize(size);
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.TableViewObj.java

/**
 * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.)
 * @param tableArg the table that should have it's columns adjusted
 *//*from  w ww .  java  2  s  .  c  o  m*/
private void initColumnSizes(final JTable tableArg) {
    ColTableModel tblModel = (ColTableModel) tableArg.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;

    TableCellRenderer headerRenderer = tableArg.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < tblModel.getColumnCount(); i++) {
        column = tableArg.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg,
                tblModel.getValueAt(0, i), false, false, 0, i);

        cellWidth = comp.getPreferredSize().width;

        /*
        if (DEBUG) {
        System.out.println("Initializing width of column "
                           + i + ". "
                           + "headerWidth = " + headerWidth
                           + "; cellWidth = " + cellWidth);
        }*/

        //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:library.Form_Library.java

License:asdf

public static void resizeColumnWidth(JTable table) {
    final TableColumnModel columnModel = table.getColumnModel();
    for (int column = 0; column < table.getColumnCount(); column++) {
        int width = 15; // Min width
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer renderer = table.getCellRenderer(row, column);
            Component comp = table.prepareRenderer(renderer, row, column);
            width = Math.max(comp.getPreferredSize().width + 1, width);
        }/*from   w w w.j  a  v a2s  .  c om*/
        if (width > 300) {
            width = 300;
        }
        columnModel.getColumn(column).setPreferredWidth(width);
    }
}

From source file:fxts.stations.ui.SideLayout.java

/**
 * Fills in an instance of <code>SideLayoutInfo</code> for the
 * current set of managed children. This requires three passes through the
 * set of children://from   w  w w. j  ava 2  s . co m
 * <ol>
 * <li>Figure out the dimensions of the layout grid.
 * <li>Determine which cells the components occupy.
 * <li>Distribute the weights and min sizes amoung the rows/columns.
 * </ol>
 * This also caches the minsizes for all the children when they are
 * first encountered (so subsequent loops don't need to ask again).
 *
 * @param aParent   the layout container
 * @param aSizeflag either <code>PREFERREDSIZE</code> or <code>MINSIZE</code>
 *
 * @return the <code>SideLayoutInfo</code> for the set of children
 */
protected SideLayoutInfo getLayoutInfo(Container aParent, int aSizeflag) {
    synchronized (aParent.getTreeLock()) {
        SideLayoutInfo r = new SideLayoutInfo();
        Component comp;
        SideConstraints constraints;
        Dimension d;
        Component[] components = aParent.getComponents();
        int compindex;
        int i;
        int j;
        int k;
        int px;
        int py;
        int pixels_diff;
        int nextSize;
        int curX, curY, curWidth, curHeight, curRow, curCol;
        double weight_diff;
        double weight;
        double start;
        double size;
        int[] xMax;
        int[] yMax;

        /*
        * Pass #1
        *
        * Figure out the dimensions of the layout grid (use a value of 1 for
        * zero or negative widths and heights).
        */

        r.width = r.height = 0;
        curRow = curCol = -1;
        xMax = new int[MAXGRIDSIZE];
        yMax = new int[MAXGRIDSIZE];
        for (compindex = 0; compindex < components.length; compindex++) {
            comp = components[compindex];
            if (!comp.isVisible()) {
                continue;
            }
            constraints = lookupConstraints(comp);
            curX = constraints.gridx;
            curY = constraints.gridy;
            curWidth = constraints.gridwidth;
            if (curWidth <= 0) {
                curWidth = 1;
            }
            curHeight = constraints.gridheight;
            if (curHeight <= 0) {
                curHeight = 1;
            }

            /* If x or y is negative, then use relative positioning: */
            if (curX < 0 && curY < 0) {
                if (curRow >= 0) {
                    curY = curRow;
                } else if (curCol >= 0) {
                    curX = curCol;
                } else {
                    curY = 0;
                }
            }
            if (curX < 0) {
                px = 0;
                for (i = curY; i < curY + curHeight; i++) {
                    px = Math.max(px, xMax[i]);
                }
                curX = px - curX - 1;
                if (curX < 0) {
                    curX = 0;
                }
            } else if (curY < 0) {
                py = 0;
                for (i = curX; i < curX + curWidth; i++) {
                    py = Math.max(py, yMax[i]);
                }
                curY = py - curY - 1;
                if (curY < 0) {
                    curY = 0;
                }
            }

            /* Adjust the grid width and height */
            for (px = curX + curWidth; r.width < px; r.width++) {
            }
            for (py = curY + curHeight; r.height < py; r.height++) {
            }

            /* Adjust the xMax and yMax arrays */
            for (i = curX; i < curX + curWidth; i++) {
                yMax[i] = py;
            }
            for (i = curY; i < curY + curHeight; i++) {
                xMax[i] = px;
            }

            /* Cache the current slave's size. */
            if (aSizeflag == PREFERREDSIZE) {
                d = comp.getPreferredSize();
            } else {
                d = comp.getMinimumSize();
            }
            constraints.minWidth = d.width;
            //constraints.setMinWidth(d.width);
            constraints.minHeight = d.height;

            /* Zero width and height must mean that this is the last item (or
            * else something is wrong). */
            if (constraints.gridheight == 0 && constraints.gridwidth == 0) {
                curRow = curCol = -1;
            }

            /* Zero width starts a new row */
            if (constraints.gridheight == 0 && curRow < 0) {
                curCol = curX + curWidth;
            }

            /* Zero height starts a new column */
            else if (constraints.gridwidth == 0 && curCol < 0) {
                curRow = curY + curHeight;
            }
        }

        /*
        * Apply minimum row/column dimensions
        */
        if (mColumnWidths != null && r.width < mColumnWidths.length) {
            r.width = mColumnWidths.length;
        }
        if (mRowHeights != null && r.height < mRowHeights.length) {
            r.height = mRowHeights.length;
        }

        /*
        * Pass #2
        *
        * Negative values for gridX are filled in with the current x value.
        * Negative values for gridY are filled in with the current y value.
        * Negative or zero values for gridWidth and gridHeight end the current
        *  row or column, respectively.
        */

        curRow = curCol = -1;
        xMax = new int[MAXGRIDSIZE];
        yMax = new int[MAXGRIDSIZE];
        for (compindex = 0; compindex < components.length; compindex++) {
            comp = components[compindex];
            if (!comp.isVisible()) {
                continue;
            }
            constraints = lookupConstraints(comp);
            curX = constraints.gridx;
            curY = constraints.gridy;
            curWidth = constraints.gridwidth;
            curHeight = constraints.gridheight;

            /* If x or y is negative, then use relative positioning: */
            if (curX < 0 && curY < 0) {
                if (curRow >= 0) {
                    curY = curRow;
                } else if (curCol >= 0) {
                    curX = curCol;
                } else {
                    curY = 0;
                }
            }
            if (curX < 0) {
                if (curHeight <= 0) {
                    curHeight += r.height - curY;
                    if (curHeight < 1) {
                        curHeight = 1;
                    }
                }
                px = 0;
                for (i = curY; i < curY + curHeight; i++) {
                    px = Math.max(px, xMax[i]);
                }
                curX = px - curX - 1;
                if (curX < 0) {
                    curX = 0;
                }
            } else if (curY < 0) {
                if (curWidth <= 0) {
                    curWidth += r.width - curX;
                    if (curWidth < 1) {
                        curWidth = 1;
                    }
                }
                py = 0;
                for (i = curX; i < curX + curWidth; i++) {
                    py = Math.max(py, yMax[i]);
                }
                curY = py - curY - 1;
                if (curY < 0) {
                    curY = 0;
                }
            }
            if (curWidth <= 0) {
                curWidth += r.width - curX;
                if (curWidth < 1) {
                    curWidth = 1;
                }
            }
            if (curHeight <= 0) {
                curHeight += r.height - curY;
                if (curHeight < 1) {
                    curHeight = 1;
                }
            }
            px = curX + curWidth;
            py = curY + curHeight;
            for (i = curX; i < curX + curWidth; i++) {
                yMax[i] = py;
            }
            for (i = curY; i < curY + curHeight; i++) {
                xMax[i] = px;
            }

            /* Make negative sizes start a new row/column */
            if (constraints.gridheight == 0 && constraints.gridwidth == 0) {
                curRow = curCol = -1;
            }
            if (constraints.gridheight == 0 && curRow < 0) {
                curCol = curX + curWidth;
            } else if (constraints.gridwidth == 0 && curCol < 0) {
                curRow = curY + curHeight;
            }

            /* Assign the new values to the gridbag slave */
            constraints.tempX = curX;
            constraints.tempY = curY;
            constraints.tempWidth = curWidth;
            constraints.tempHeight = curHeight;
        }

        /*
        * Apply minimum row/column dimensions and weights
        */
        if (mColumnWidths != null) {
            System.arraycopy(mColumnWidths, 0, r.minWidth, 0, mColumnWidths.length);
        }
        if (mRowHeights != null) {
            System.arraycopy(mRowHeights, 0, r.minHeight, 0, mRowHeights.length);
        }
        if (mColumnWeights != null) {
            System.arraycopy(mColumnWeights, 0, r.weightX, 0, mColumnWeights.length);
        }
        if (mRowWeights != null) {
            System.arraycopy(mRowWeights, 0, r.weightY, 0, mRowWeights.length);
        }

        /*
        * Pass #3
        *
        * Distribute the minimun widths and weights:
        */

        nextSize = Integer.MAX_VALUE;
        for (i = 1; i != Integer.MAX_VALUE; i = nextSize, nextSize = Integer.MAX_VALUE) {
            for (compindex = 0; compindex < components.length; compindex++) {
                comp = components[compindex];
                if (!comp.isVisible()) {
                    continue;
                }
                constraints = lookupConstraints(comp);
                if (constraints.tempWidth == i) {
                    px = constraints.tempX + constraints.tempWidth; /* right column */

                    /*
                    * Figure out if we should use this slave\'s weight.  If the weight
                    * is less than the total weight spanned by the width of the cell,
                    * then discard the weight.  Otherwise split the difference
                    * according to the existing weights.
                    */

                    weight_diff = constraints.weightx;
                    for (k = constraints.tempX; k < px; k++) {
                        weight_diff -= r.weightX[k];
                    }
                    if (weight_diff > 0.0) {
                        weight = 0.0;
                        for (k = constraints.tempX; k < px; k++) {
                            weight += r.weightX[k];
                        }
                        for (k = constraints.tempX; weight > 0.0 && k < px; k++) {
                            double wt = r.weightX[k];
                            double dx = (wt * weight_diff) / weight;
                            r.weightX[k] += dx;
                            weight_diff -= dx;
                            weight -= wt;
                        }
                        /* Assign the remainder to the rightmost cell */
                        r.weightX[px - 1] += weight_diff;
                    }

                    /*
                    * Calculate the minWidth array values.
                    * First, figure out how wide the current slave needs to be.
                    * Then, see if it will fit within the current minWidth values.
                    * If it will not fit, add the difference according to the
                    * weightX array.
                    */

                    pixels_diff = constraints.minWidth + constraints.ipadx + constraints.insets.left
                            + constraints.insets.right;
                    for (k = constraints.tempX; k < px; k++) {
                        pixels_diff -= r.minWidth[k];
                    }
                    if (pixels_diff > 0) {
                        weight = 0.0;
                        for (k = constraints.tempX; k < px; k++) {
                            weight += r.weightX[k];
                        }
                        for (k = constraints.tempX; weight > 0.0 && k < px; k++) {
                            double wt = r.weightX[k];
                            int dx = (int) ((wt * (double) pixels_diff) / weight);
                            r.minWidth[k] += dx;
                            pixels_diff -= dx;
                            weight -= wt;
                        }
                        /* Any leftovers go into the rightmost cell */
                        r.minWidth[px - 1] += pixels_diff;
                    }
                } else if (constraints.tempWidth > i && constraints.tempWidth < nextSize) {
                    nextSize = constraints.tempWidth;
                }
                if (constraints.tempHeight == i) {
                    py = constraints.tempY + constraints.tempHeight; /* bottom row */

                    /*
                    * Figure out if we should use this slave's weight.  If the weight
                    * is less than the total weight spanned by the height of the cell,
                    * then discard the weight.  Otherwise split it the difference
                    * according to the existing weights.
                    */

                    weight_diff = constraints.weighty;
                    for (k = constraints.tempY; k < py; k++) {
                        weight_diff -= r.weightY[k];
                    }
                    if (weight_diff > 0.0) {
                        weight = 0.0;
                        for (k = constraints.tempY; k < py; k++) {
                            weight += r.weightY[k];
                        }
                        for (k = constraints.tempY; weight > 0.0 && k < py; k++) {
                            double wt = r.weightY[k];
                            double dy = (wt * weight_diff) / weight;
                            r.weightY[k] += dy;
                            weight_diff -= dy;
                            weight -= wt;
                        }
                        /* Assign the remainder to the bottom cell */
                        r.weightY[py - 1] += weight_diff;
                    }

                    /*
                    * Calculate the minHeight array values.
                    * First, figure out how tall the current slave needs to be.
                    * Then, see if it will fit within the current minHeight values.
                    * If it will not fit, add the difference according to the
                    * weightY array.
                    */

                    pixels_diff = constraints.minHeight + constraints.ipady + constraints.insets.top
                            + constraints.insets.bottom;
                    for (k = constraints.tempY; k < py; k++) {
                        pixels_diff -= r.minHeight[k];
                    }
                    if (pixels_diff > 0) {
                        weight = 0.0;
                        for (k = constraints.tempY; k < py; k++) {
                            weight += r.weightY[k];
                        }
                        for (k = constraints.tempY; weight > 0.0 && k < py; k++) {
                            double wt = r.weightY[k];
                            int dy = (int) ((wt * (double) pixels_diff) / weight);
                            r.minHeight[k] += dy;
                            pixels_diff -= dy;
                            weight -= wt;
                        }
                        /* Any leftovers go into the bottom cell */
                        r.minHeight[py - 1] += pixels_diff;
                    }
                } else if (constraints.tempHeight > i && constraints.tempHeight < nextSize) {
                    nextSize = constraints.tempHeight;
                }
            }
        }
        return r;
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.)
 * @param tableArg the table that should have it's columns adjusted
 *///from   ww  w .  j  a v  a  2s .  com
private void initColumnSizes(final JTable tableArg, final JButton theSaveBtn) throws Exception {
    TableModel tblModel = tableArg.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;

    Element uploadDefs = null;
    if (WorkbenchTask.isCustomizedSchema()) {
        uploadDefs = XMLHelper.readFileToDOM4J(
                new File(UIRegistry.getAppDataDir() + File.separator + "specify_workbench_upload_def.xml"));
    } else {
        uploadDefs = XMLHelper.readDOMFromConfigDir("specify_workbench_upload_def.xml");
    }

    //UIRegistry.getInstance().hookUpUndoableEditListener(cellEditor);

    Vector<WorkbenchTemplateMappingItem> wbtmis = new Vector<WorkbenchTemplateMappingItem>();
    wbtmis.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    Collections.sort(wbtmis);

    DBTableIdMgr databaseSchema = WorkbenchTask.getDatabaseSchema();

    columnMaxWidths = new Integer[tableArg.getColumnCount()];
    for (int i = 0; i < wbtmis.size() /*tableArg.getColumnCount()*/; i++) {
        TableCellRenderer headerRenderer = tableArg.getColumnModel().getColumn(i).getHeaderRenderer();
        WorkbenchTemplateMappingItem wbtmi = wbtmis.elementAt(i);

        // Now go retrieve the data length
        int fieldWidth = WorkbenchDataItem.getMaxWBCellLength();
        DBTableInfo ti = databaseSchema.getInfoById(wbtmi.getSrcTableId());
        if (ti != null) {
            DBFieldInfo fi = ti.getFieldByName(wbtmi.getFieldName());
            if (fi != null) {
                wbtmi.setFieldInfo(fi);
                //System.out.println(fi.getName()+"  "+fi.getLength()+"  "+fi.getType());
                if (RecordTypeCodeBuilder.getTypeCode(fi) == null && fi.getLength() > 0) {
                    fieldWidth = Math.min(fi.getLength(), WorkbenchDataItem.getMaxWBCellLength());
                }
            } else {
                log.error("Can't find field with name [" + wbtmi.getFieldName() + "]");
            }
        } else {
            log.error("Can't find table [" + wbtmi.getSrcTableId() + "]");
        }
        columnMaxWidths[i] = new Integer(fieldWidth);
        GridCellEditor cellEditor = getCellEditor(wbtmi, fieldWidth, theSaveBtn, uploadDefs);
        column = tableArg.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg,
                tblModel.getValueAt(0, i), false, false, 0, i);

        cellWidth = comp.getPreferredSize().width;

        //comp.setBackground(Color.WHITE);

        int maxWidth = headerWidth + 10;
        TableModel m = tableArg.getModel();
        FontMetrics fm = comp.getFontMetrics(comp.getFont());
        for (int row = 0; row < tableArg.getModel().getRowCount(); row++) {
            String text = m.getValueAt(row, i).toString();
            maxWidth = Math.max(maxWidth, fm.stringWidth(text) + 10);
            //log.debug(i+" "+maxWidth);
        }

        //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
        //log.debug(Math.max(maxWidth, cellWidth));
        //log.debug(Math.min(Math.max(maxWidth, cellWidth), 400));
        column.setPreferredWidth(Math.min(Math.max(maxWidth, cellWidth), 400));

        column.setCellEditor(cellEditor);
    }
    //tableArg.setCellEditor(cellEditor);
}

From source file:op.tools.SYSTools.java

public static void packColumn(JTable table, int vColIndex, int margin) {
    TableModel model = table.getModel();
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width = 0;

    // Get width of column header
    TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null) {
        renderer = table.getTableHeader().getDefaultRenderer();
    }//from   www .  ja v a 2 s  .  c  o m
    Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
    width = comp.getPreferredSize().width;

    // Get maximum width of column data
    for (int r = 0; r < table.getRowCount(); r++) {
        renderer = table.getCellRenderer(r, vColIndex);
        comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false, r,
                vColIndex);
        width = Math.max(width, comp.getPreferredSize().width);
    }

    // Add margin
    width += 2 * margin;
    // Set the width
    col.setPreferredWidth(width);

    OPDE.debug("packColumn/3: col=" + vColIndex + "  width=" + width);
}

From source file:org.apache.cayenne.swing.TableBinding.java

protected void resizeColumns(Object[] sampleLongValues) {

    TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
    TableColumnModel columnModel = table.getColumnModel();
    TableModel tableModel = table.getModel();

    for (int i = 0; i < columnModel.getColumnCount(); i++) {

        TableColumn column = columnModel.getColumn(i);

        Component header = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false,
                false, 0, 0);/*  www.jav  a  2  s .co  m*/
        int headerWidth = header.getPreferredSize().width;

        if (sampleLongValues[i] != null) {
            Component bigCell = table.getDefaultRenderer(tableModel.getColumnClass(i))
                    .getTableCellRendererComponent(table, sampleLongValues[i], false, false, 0, i);
            int cellWidth = bigCell.getPreferredSize().width;
            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        } else {
            column.setPreferredWidth(headerWidth);
        }
    }
}

From source file:org.apache.jmeter.testbeans.gui.GenericTestBeanCustomizer.java

/**
 * Initialize the GUI.//from ww w .  j a v  a 2  s .  co m
 */
private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final)
    setLayout(new GridBagLayout());

    GridBagConstraints cl = new GridBagConstraints(); // for labels
    cl.gridx = 0;
    cl.anchor = GridBagConstraints.EAST;
    cl.insets = new Insets(0, 1, 0, 1);

    GridBagConstraints ce = new GridBagConstraints(); // for editors
    ce.fill = GridBagConstraints.BOTH;
    ce.gridx = 1;
    ce.weightx = 1.0;
    ce.insets = new Insets(0, 1, 0, 1);

    GridBagConstraints cp = new GridBagConstraints(); // for panels
    cp.fill = GridBagConstraints.BOTH;
    cp.gridx = 1;
    cp.gridy = GridBagConstraints.RELATIVE;
    cp.gridwidth = 2;
    cp.weightx = 1.0;

    JPanel currentPanel = this;
    String currentGroup = DEFAULT_GROUP;
    int y = 0;

    for (int i = 0; i < editors.length; i++) {
        if (editors[i] == null) {
            continue;
        }

        if (log.isDebugEnabled()) {
            log.debug("Laying property " + descriptors[i].getName());
        }

        String g = group(descriptors[i]);
        if (!currentGroup.equals(g)) {
            if (currentPanel != this) {
                add(currentPanel, cp);
            }
            currentGroup = g;
            currentPanel = new JPanel(new GridBagLayout());
            currentPanel.setBorder(
                    BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), groupDisplayName(g)));
            cp.weighty = 0.0;
            y = 0;
        }

        Component customEditor = editors[i].getCustomEditor();

        boolean multiLineEditor = false;
        if (customEditor.getPreferredSize().height > 50 || customEditor instanceof JScrollPane
                || descriptors[i].getValue(MULTILINE) != null) {
            // TODO: the above works in the current situation, but it's
            // just a hack. How to get each editor to report whether it
            // wants to grow bigger? Whether the property label should
            // be at the left or at the top of the editor? ...?
            multiLineEditor = true;
        }

        JLabel label = createLabel(descriptors[i]);
        label.setLabelFor(customEditor);

        cl.gridy = y;
        cl.gridwidth = multiLineEditor ? 2 : 1;
        cl.anchor = multiLineEditor ? GridBagConstraints.CENTER : GridBagConstraints.EAST;
        currentPanel.add(label, cl);

        ce.gridx = multiLineEditor ? 0 : 1;
        ce.gridy = multiLineEditor ? ++y : y;
        ce.gridwidth = multiLineEditor ? 2 : 1;
        ce.weighty = multiLineEditor ? 1.0 : 0.0;

        cp.weighty += ce.weighty;

        currentPanel.add(customEditor, ce);

        y++;
    }
    if (currentPanel != this) {
        add(currentPanel, cp);
    }

    // Add a 0-sized invisible component that will take all the vertical
    // space that nobody wants:
    cp.weighty = 0.0001;
    add(Box.createHorizontalStrut(0), cp);
}

From source file:org.dwfa.ace.graph.AceGraphRenderer.java

/**
 * Labels the specified vertex with the specified label.
 * Uses the font specified by this instance's
 * <code>VertexFontFunction</code>. (If the font is unspecified, the
 * existing//from  w w  w.ja va  2 s  .c o m
 * font for the graphics context is used.) If vertex label centering
 * is active, the label is centered on the position of the vertex; otherwise
 * the label is offset slightly.
 */
protected void labelVertex(Graphics g, Vertex v, String label, int x, int y) {
    Component component = prepareRenderer(graphLabelRenderer, label, isPicked(v), v);

    Dimension d = component.getPreferredSize();

    int h_offset;
    int v_offset;
    if (centerVertexLabel) {
        h_offset = -d.width / 2;
        v_offset = -d.height / 2;

    } else {
        Rectangle2D bounds = vertexShapeFunction.getShape(v).getBounds2D();
        h_offset = (int) (bounds.getWidth() / 2) + 5;
        v_offset = (int) (bounds.getHeight() / 2) + 5 - d.height;
    }

    component.setBackground(Color.white);
    rendererPane.paintComponent(g, component, screenDevice, x + h_offset, y + v_offset, d.width, d.height,
            true);

}

From source file:org.kineticsystem.commons.layout.TetrisLayout.java

/**
 * Add the specified component to the layout, using the specified
 * constraint object.//from  www.  j  a v a 2  s. c  o m
 * @param comp The component to be added
 * @param constraints Where/how the component is added to the layout.
 */
public void addLayoutComponent(Component comp, Object constraints) {

    if (constraints == null) {
        constraints = new Cell();
    }
    if (constraints instanceof Cell) {

        Cell cell = (Cell) constraints;
        if (cell.getRows() < 0 || cell.getCols() < 0) {
            logger.fatal("Cannot add to layout: " + "cell must have positive row and column number!");
            System.exit(TetrisLayout.FATAL_ERROR);
        }
        setConstraints(comp, cell);

        // Store a copy of all component dimensions.

        Size cd = new Size();
        cd.setMaximumWidth(comp.getMaximumSize().getWidth());
        cd.setMaximumHeight(comp.getMaximumSize().getHeight());
        cd.setMinimumWidth(comp.getMinimumSize().getWidth());
        cd.setMinimumHeight(comp.getMinimumSize().getHeight());
        cd.setPreferredWidth(comp.getPreferredSize().getWidth());
        cd.setPreferredHeight(comp.getPreferredSize().getHeight());

        // Check dimensions.

        if (cd.getMinimumWidth() > cd.getPreferredWidth()) {
            logger.warn("Component minimum width is greater than preferred"
                    + " width: set value to preferred size!\n" + cd);
            cd.setMinimumWidth(cd.getPreferredWidth());
        }
        if (cd.getMaximumWidth() < cd.getPreferredWidth()) {
            logger.warn("Component maximum width is less than preferred"
                    + " width: set value to preferred size!\n" + cd);
            cd.setMaximumWidth(cd.getPreferredWidth());
        }
        if (cd.getMinimumHeight() > cd.getPreferredHeight()) {
            logger.warn("Component minimum height is greater than preferred"
                    + " height: set value to preferred size!\n" + cd);
            cd.setMinimumHeight(cd.getPreferredHeight());
        }
        if (cd.getMaximumHeight() < cd.getPreferredHeight()) {
            logger.warn("Component maximum height is less than preferred"
                    + " height: set value to preferred size!\n" + cd);
            cd.setMaximumHeight(cd.getPreferredHeight());
        }

        componentSizes.put(comp, cd);

    } else if (constraints != null) {
        logger.fatal("Cannot add to layout: constraint must be a Cell!");
        System.exit(TetrisLayout.FATAL_ERROR);
    }
}