Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.awt.Component;
import java.awt.Container;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import java.util.List;

public class Main {
    /**
     * Lays out a list of controls in a compact grid-layout, meaning that each
     * cell in the grid only takes up it's preferred size.
     * 
     * @param parent the parent <code>Container</code>
     * @param colCount the number of columns
     * @param padding the number of pixels to pad between cells
     * @param components a <code>List</code> of <code>Component</code>s that
     *        should be added to <code>parent</code>
     */
    public static void makeCompactGrid(Container parent, int colCount, int padding,
            List<? extends Component> components) {

        parent.setLayout(new GridBagLayout());

        final int componentCount = components.size();
        final int rowCount = getRowCount(componentCount, colCount);

        final GridBagConstraints c = new GridBagConstraints();
        final int realPadding = (padding / 2);

        c.gridheight = 1;
        c.gridwidth = 1;
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1;
        c.weighty = 1;
        c.insets = new Insets(realPadding, realPadding, realPadding, realPadding);

        for (int i = 0; i < (rowCount * colCount); i++) {
            final int x = (i % colCount);
            final int y = (i / colCount);

            c.gridx = x;
            c.gridy = y;

            parent.add(components.get(i), c);
        }
    }

    private static int getRowCount(int componentCount, int colCount) {
        int rowCount = (componentCount / colCount);
        if ((componentCount % colCount) != 0) {
            rowCount++;
        }
        return rowCount;
    }
}