package comboBoxColorChooser;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Color_Combo extends JPanel implements ChangeListener,
		ActionListener {

	private JComboBox combo;
	private JColorChooser chooser;
	private JTextField text;
	private boolean floatSelected = true;

	public Color_Combo() {

		String[] combolist = { "float", "hex" };
		combo = new JComboBox(combolist);
		
		combo.setActionCommand((String) combo.getSelectedItem());
		combo.addActionListener(this);

		chooser = new JColorChooser(Color.CYAN);
		chooser.getSelectionModel().addChangeListener(this);

		text = new JTextField("Sample Text!");
		text.setBackground(chooser.getColor());

		this.add(combo);
		this.add(chooser);
		this.add(text);

	}

	public void stateChanged(ChangeEvent e) {

		float[] comps = chooser.getColor().getColorComponents(null);

		String comstring = "";

		if (floatSelected) {
			for (int i = 0; i < comps.length; i++) {
				comstring += comps[i] + ", ";
			}
		} else {		
			int r = chooser.getColor().getRed();
			int g = chooser.getColor().getGreen();
			int b = chooser.getColor().getBlue();
			
			comstring = String.format("#%02x%02x%02x", r, g, b);
		}
		text.setText(comstring);
		combo.setBackground(chooser.getColor());
	}

	public void actionPerformed(ActionEvent e) {
		if ((((JComboBox) e.getSource()).getSelectedItem()).equals("float")) {
			text.setText("You selected float!");
			floatSelected = true;
		} // if (e.getActionCommand().equals("hex")) {
		else {
			text.setText("You selected hex!");
			floatSelected = false;
		}
	}

	public static void createAndShowGUI() {

		JFrame frame = new JFrame("COMBO BOX AND COLOR CHOOSER");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		Color_Combo content = new Color_Combo();
		content.setOpaque(true);
		frame.setContentPane(content);

		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {

		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});

	}

}
