/************************************************** * Author: Morrison * Date: 16 Mar 202021 **************************************************/ import javafx.application.Application; import javafx.application.Platform; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.canvas.GraphicsContext; import javafx.scene.canvas.Canvas; import javafx.scene.paint.Color; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import java.util.ArrayList; public class Squeak extends Application { private ArrayList shapes = new ArrayList<>(); public Squeak() { } @Override public void init() { } @Override public void start(Stage primary) { primary.setTitle("Mouse Demonstration"); BorderPane bp = new BorderPane(); primary.setScene(new Scene(bp)); Canvas canvas = new Canvas(700, 500); GraphicsContext pen = canvas.getGraphicsContext2D(); //Puzzler: turn canvas red //pen.setFill(Color.RED); //pen.fillRect(0, 0, canvas.getWidth(), canvas.getHeight()); /* puzzler #2 * when the mouse enters the canvas, turn it red. * when it exits turn it white. */ canvas.setOnMouseEntered( e -> { pen.setFill(Color.RED); pen.fillRect(0, 0, canvas.getWidth(), canvas.getHeight()); redrawShapes(pen); }); canvas.setOnMouseExited( e -> { pen.setFill(Color.WHITE); pen.fillRect(0, 0, canvas.getWidth(), canvas.getHeight()); redrawShapes(pen); }); /* * puzzler #3: * When the user click on the canvas, have a blue ball of * radius 50 pixels appear centered at the click point. */ canvas.setOnMouseClicked( e -> { Drawable b = new Square(e.getX(), e.getY(), 50, Color.BLUE); shapes.add(b); b.draw(pen); }); bp.setCenter(canvas); bp.setTop(buildMenus()); primary.show(); } private MenuBar buildMenus() { MenuBar mbar = new MenuBar(); Menu colorMenu = new Menu("Color"); Menu shapeMenu = new Menu("Shape"); mbar.getMenus().addAll(colorMenu, shapeMenu); MenuItem redItem = new MenuItem("RED"); MenuItem blueItem = new MenuItem("BLUE"); MenuItem greenItem = new MenuItem("GREEN"); colorMenu.getItems().addAll(redItem, greenItem, blueItem); return mbar; } private void redrawShapes(GraphicsContext pen) { for(Drawable b: shapes) { b.draw(pen); } } @Override public void stop() { } }