import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.*; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.event.ActionEvent; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; /** * Displays a coloured square to the canvas * * @author Dave Slemon * @version v100 */ public class SquareApp extends Application { // TODO: Instance Variables for View Components and Model private Button changeColorButton; private TextField inputBox; private GraphicsContext gc; // TODO: Private Event Handlers and Helper Methods private void drawRoutine() { //background ivory colour gc.setFill(Color.web("lightgray")); gc.fillRect(0,0,400,290); //the square's colour gc.setFill(Color.web(inputBox.getText())); gc.fillRect(150,100,100,100); } private void redraw(ActionEvent e) { drawRoutine(); } /** * This is where you create your components and the model and add event * handlers. * * @param stage The main stage * @throws Exception */ @Override public void start(Stage stage) throws Exception { Pane root = new Pane(); Scene scene = new Scene(root, 400, 400); // set the size here stage.setTitle("Coloured Square App"); // set the window title here stage.setScene(scene); // TODO: Add your GUI-building code here scene.getStylesheets().addAll("myStyles.css"); // 1. Create the model Canvas canvas = new Canvas(400,300); gc = canvas.getGraphicsContext2D(); // 2. Create the GUI components changeColorButton = new Button("Change Colour"); inputBox = new TextField("red"); // 3. Add components to the root root.getChildren().addAll(canvas,changeColorButton,inputBox); // 4. Configure the components (colors, fonts, size, location) changeColorButton.relocate(170,300); inputBox.relocate(30,300); drawRoutine(); // 5. Add Event Handlers and do final setup changeColorButton.setOnAction(this::redraw); // 6. Show the stage stage.show(); } /** * Make no changes here. * * @param args unused */ public static void main(String[] args) { launch(args); } }