import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Popup;
import javafx.stage.Stage;

/**
 * Modified sample from:
 * https://docs.oracle.com/javafx/2/ui_controls/color-picker.htm
 */
public class Test extends Application {
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) {
		stage.setTitle("ColorPicker");
		Scene scene = new Scene(new HBox(20), 400, 100);
		HBox box = (HBox) scene.getRoot();
		box.setPadding(new Insets(5, 5, 5, 5));

		Button colourButton = new Button("Click Me");
		colourButton.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				ColourSelectorPopup colourSelectorPopup = new ColourSelectorPopup();
				colourSelectorPopup.show(colourButton);
			}
		});

		Text text = new Text("Try the color picker!");

		box.getChildren().addAll(colourButton, text);

		stage.setScene(scene);
		stage.show();
	}

// colour selector pop-up
	private class ColourSelectorPopup {
		protected Popup popup;
		private ColorPicker colorPicker;

		public ColourSelectorPopup() {
			buildUI();
		}

		private void buildUI() {
// colour picker
			colorPicker = new ColorPicker(Color.AQUA);

			colorPicker.setOnAction(new EventHandler<ActionEvent>() {
				@Override
				public void handle(ActionEvent evt) {
					Color colourPickerColour = colorPicker.getValue();
					System.out.println("selected colour: " + colourPickerColour);
					hide();
				}
			});

// pop up
			popup = new Popup();
			popup.getContent().add(colorPicker);
			popup.setAutoHide(true);
			popup.setHideOnEscape(true);
		}

		public void show(Node ownerNode) {
//buildUI(); // build now that request to show has been made

			double screenX = screenCoordinates(ownerNode).getMinX();
			double screenY = screenCoordinates(ownerNode).getMinY();
			popup.show(ownerNode, screenX + 64, screenY);
		}

		public void hide() {
			popup.hide();
		}

		private Bounds screenCoordinates(Node node) {
			Bounds bounds = node.getBoundsInLocal();
			Bounds screenBounds = node.localToScreen(bounds);
			return screenBounds;
		}

	} // class ColourSelectorPopup
} // class ColorPickerSample