import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/**
 * A basic JavaFX application with buttons, custom painting on a canvas, and
 * event handling.
 */
public class SimpleGUIDemoAlt extends Application {

	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) throws Exception {
		stage.setTitle("GUI Demo");

		BorderPane root = new BorderPane();
		Scene scene = new Scene(root);
		stage.setScene(scene);
		// keep the window from being resized by the user
		stage.setResizable(false);

		// canvas with two circles
		Canvas canvas = new Canvas(200, 100);
		drawCircles(canvas,Color.BLACK);

		// buttons
		Button red = new Button("red");
		red.setOnAction(e -> drawCircles(canvas, Color.RED));
		Button green = new Button("green");
		green.setOnAction(e -> drawCircles(canvas, Color.GREEN));
		Button blue = new Button("blue");
		blue.setOnAction(e -> drawCircles(canvas, Color.BLUE));

		HBox btnpane = new HBox();
		btnpane.getChildren().addAll(red, green, blue);
		// allow buttons to fill the width of the window
		HBox.setHgrow(red, Priority.ALWAYS);
		HBox.setHgrow(green, Priority.ALWAYS);
		HBox.setHgrow(blue, Priority.ALWAYS);
		// allow buttons to grow beyond their preferred size
		red.setMaxWidth(Double.POSITIVE_INFINITY);
		green.setMaxWidth(Double.POSITIVE_INFINITY);
		blue.setMaxWidth(Double.POSITIVE_INFINITY);

		// add nodes to the root of the scene graph
		root.setTop(btnpane);
		root.setCenter(canvas);

		stage.show();
	}

	private void drawCircles(Canvas canvas, Color color) {
		GraphicsContext g = canvas.getGraphicsContext2D();
		double w = canvas.getWidth(), h = canvas.getHeight();

		g.clearRect(0, 0, w, h);

		g.setFill(color);
		g.setStroke(color); // outline in same color as fill
		g.fillOval(0, 0, w / 2, h);
		g.fillOval(w / 2, 0, w / 2, h);

	}
}
