ITI0011:praktikum 9 N14

Allikas: Kursused
Mine navigeerimisribale Mine otsikasti

Tagasi ITI0011 lehele.

Üldine

Praktikum: 30.10.2014 kell 14:00

Teemad:

Koodinäite

<source lang="java"> import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage;

public class Main extends Application {

public static void main(String[] args) { // TODO Auto-generated method stub launch(args); }

private double oldX = 0.0; private double count = 0;

@Override public void start(Stage primaryStage) throws Exception { BorderPane root = new BorderPane(); Scene scene = new Scene(root, 400, 400);


MenuBar menuBar = new MenuBar(); Menu menuFile = new Menu("File"); Menu menuView = new Menu("View"); MenuItem menuFileSave = new MenuItem("Save"); menuBar.getMenus().add(menuFile); menuBar.getMenus().add(menuView); menuFile.getItems().add(menuFileSave);

root.setTop(menuBar);

primaryStage.setScene(scene); primaryStage.show();

Pane main = new Pane(); root.setCenter(main);

Rectangle r = new Rectangle(100, 100, 40, 90); r.setFill(Color.TRANSPARENT); r.setStroke(Color.BLUE); main.getChildren().add(r);

EventHandler<MouseEvent> myHandler = new EventHandler<MouseEvent>() {

@Override public void handle(MouseEvent event) { if (event.getEventType() == MouseEvent.MOUSE_PRESSED) { //System.out.println(event); Rectangle r = new Rectangle(event.getX(), event.getY(), 20, 20); main.getChildren().add(r); oldX = event.getX(); } else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) { count += 0.1; for (Node n : main.getChildren()) { if (n instanceof Rectangle) { Rectangle r = (Rectangle)n; // x = x + dx r.setX(r.getX() + (event.getX() - oldX)); r.setWidth(r.getWidth() + count); r.setHeight(r.getHeight() + count); } } oldX = event.getX(); }

} };

main.addEventHandler(MouseEvent.MOUSE_PRESSED, myHandler); main.addEventHandler(MouseEvent.MOUSE_DRAGGED, myHandler);

}

} </source>

Exercise

Create an application which allows the user to draw a rectangle. There are several options how to achieve this:

  • using mouse dragging: the starting point is fixed when the dragging starts (mouse press), the opposite corner moves along while dragging. if the dragging ends, the rectangle is fixed.
  • using clicking: when clicking first time, one point is fixed, when clicking another time, the opposite corner is fixed (and rectangle is drawn).
  • some other way

Optional requirements:

  • more than one rectangle can be drawn