Source of MousePaint.java


  1: import javafx.application.Application;
  2: import javafx.scene.canvas.Canvas;
  3: import javafx.scene.Scene;
  4: import javafx.stage.Stage;
  5: import javafx.scene.Group;
  6: import javafx.scene.canvas.GraphicsContext;
  7: import javafx.scene.paint.Color;
  8: import javafx.scene.input.MouseEvent;
  9: import javafx.event.EventHandler;
 10: import java.util.Random;
 11: 
 12: /**
 13: This program draws a circle of random color
 14: at the location of the mouse whenever the mouse
 15: moves.
 16: */
 17: public class MousePaint extends Application
 18: {
 19:    private Random rnd = new Random();
 20: 
 21:    public static void main(String[] args) {
 22:       Application.launch(args);
 23:    }
 24: 
 25:    @Override
 26:    public void start(Stage primaryStage) throws Exception {
 27: 
 28:       Group root = new Group();
 29:       Canvas canvas = new Canvas(650, 600);
 30:       GraphicsContext gc = canvas.getGraphicsContext2D();
 31: 
 32:           // When the mouse is pressed erase the
 33:           // screen by drawing a white rectangle on the
 34:           // entire canvas
 35:           canvas.setOnMousePressed(new EventHandler<MouseEvent>()
 36:           {
 37:         @Override
 38:         public void handle(MouseEvent event)
 39:         {
 40:                 gc.setFill(Color.WHITE);
 41:           gc.fillRect(0,0,canvas.getWidth(),canvas.getHeight());
 42:         }
 43:       });
 44: 
 45:           // When the mouse is moved get a random color
 46:           // and draw a circle at the mouse's coordinates
 47:           canvas.setOnMouseMoved(new EventHandler<MouseEvent>()
 48:           {
 49:          @Override public void handle(MouseEvent event)
 50:          {
 51:                // Get a random color
 52:            gc.setFill(Color.rgb(rnd.nextInt(255),
 53:                 rnd.nextInt(255),
 54:                 rnd.nextInt(255)));
 55:            gc.fillOval(event.getX(),event.getY(),100,100);
 56:          }
 57:       });
 58: 
 59:       root.getChildren().add(canvas);
 60:       primaryStage.setScene(new Scene(root));
 61:       primaryStage.setTitle("Mouse Paint");
 62:       primaryStage.show();
 63:    }
 64: }