
package org.openspml.browser;

import java.util.ArrayList;

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;
import javax.swing.event.*;

/**
 * Simple JPanel extension that uses a GridBag layout to accomplish
 * the usual two column editing form.  The form contains a set
 * of components arranged vertically.  The form has two columns, 
 * the first containing the title of the component, and the second 
 * the component itself.  Titles are left justified.
 */
public class SimpleForm extends JPanel {

    Container _target;
    GridBagConstraints _cons;

    public static class Field {

	JLabel _label;
	JComponent _component;

	public Field(JLabel l, JComponent c) {
	    _label = l;
	    _component = c;
	}

	public void setVisible(boolean b) {
	    _label.setVisible(b);
	    _component.setVisible(b);
	}
    }

    public SimpleForm() {
	this(true);
    }

    /**
     * Added the "noCenter" flag to wrap the GridBagLayout
     * in another panel so it will float to the top of the
     * available space.
     */
    public SimpleForm(boolean noCenter) {

	_cons = new GridBagConstraints();
	_cons.anchor = GridBagConstraints.NORTHWEST;

	_target = this;
	if (noCenter) {
	    JPanel p = new JPanel();	
	    add(p);	
	    _target = p;
	}

	_target.setLayout(new GridBagLayout());
	addSpacer();
    }

    /**
     * Clear the contents of the form, useful when dyamically generating
     * them.  Since we may wrap a panel have to provide this.
     */
    public void clear() {
	_target.removeAll();
    }

    public void addSpacer() {
	add(" ", new JLabel(" "));
    }

    public Field add(String name, JComponent component) {

	// name
	// label alighment may be SwingConstants.LEFT, CENTER, RIGHT,
	// LEADING, TRAILING, the default is against the leading edge
	// centered vertically.  Not sure what the difference between
	// LEFT AND LEADING is.
	JLabel l = new JLabel(name);
	_target.add(l, _cons);

	// horizontal gap
	_target.add(Box.createHorizontalStrut(10), _cons);

	// component, fills the remainder of the row
	_cons.gridwidth = GridBagConstraints.REMAINDER;
	_cons.weightx = 1.0;
	_target.add(component, _cons);
	
	// vertical gap
	_cons.weightx = 0;
	_target.add(Box.createVerticalStrut(3), _cons);

	// reset for the next call
	_cons.gridwidth = 1;

	return new Field(l, component);
    }

}

