All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.yaoqiang.collaboration.ComboPanel Maven / Gradle / Ivy

package org.yaoqiang.collaboration;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.yaoqiang.util.Resources;


/**
 * ComboPanel
 * 
 * @author Shi Yaoqiang([email protected])
 */
public class ComboPanel extends JPanel {

	private static final long serialVersionUID = -2708869980534018181L;

	Dimension textDim = new Dimension(120, 27);

	protected String key;

	protected JComboBox jcb;

	public ComboPanel(String key, Collection choices, boolean hasEmpty, boolean isEditable, boolean isEnabled) {
		this.setLayout(new BorderLayout());
		this.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
		this.key = key;
		
		JLabel jl = new JLabel(Resources.get(key) + ": ");

		List chs = new ArrayList(choices);
		jcb = new JComboBox(new Vector(chs));
		resetComboDimension(chs);
		
		jcb.setEditable(isEditable);
		jcb.setEnabled(isEnabled);

		this.add(jl, BorderLayout.WEST);
		this.add(Box.createHorizontalGlue(), BorderLayout.EAST);
		this.add(jcb, BorderLayout.CENTER);

	}
	
	public Object getSelectedItem() {
		Object obj = null;
		if (jcb.isEditable()) {
			obj = jcb.getEditor().getItem();
		} else {
			obj = jcb.getSelectedItem();
		}
		if (obj != null) {
			return obj.toString();
		}
		return "";
	}

	public int getSelectedIndex() {
		return jcb.getSelectedIndex();
	}
	
	public void resetComboDimension(Collection choices) {
		double w = 0;
		if (choices != null) {
			double longest = 0;
			for (Object ch : choices) {
				w = getFontMetrics(getFont()).stringWidth(ch.toString());
				if (w > longest) {
					longest = w;
				}
			}
			w = longest + 25;
		}
		if (w < textDim.width)
			w = textDim.width;
		
		Dimension dim = new Dimension((int) w, textDim.height);
		jcb.setMinimumSize(dim);
		jcb.setMaximumSize(dim);
		jcb.setPreferredSize(dim);
	}

	public JComboBox getComboBox() {
		return jcb;
	}

	public void setSelectedItem(String item) {
		jcb.setSelectedItem(item);
	}

	public void setEnabled(boolean b) {
		super.setEnabled(b);
		jcb.setEnabled(b);
	}

	public void requestFocus() {
		jcb.requestFocus();
	}

	public void addActionListener(ActionListener l) {
		jcb.addActionListener(l);
	}

	public boolean isEmpty() {
		Object o = getSelectedItem();
		if (o == null) {
			return true;
		}
		if (o instanceof String) {
			return ((String) o).trim().equals("");
		}
		return false;
	}

}