@FXML
  void processNewGame(ActionEvent event) {
    GestorLogs.registrarLog("Creando nuevo Juego...");
    String fxml = ConstantesFXML.FXML_CREAR_JUEGO;

    try {
      Parent root;
      Stage stage = new Stage();
      FXMLLoader loader = ScreensFramework.getLoader(fxml);

      root = (Parent) loader.load();
      CrearJuegoController controller = (CrearJuegoController) loader.getController();
      controller.setPrevStage(currentStage);
      controller.setUsuarioLogueado(usuarioLogueado);

      Scene scene = new Scene(root);
      stage.setScene(scene);
      stage.setTitle("Monopoly - Nuevo Juego");
      stage.centerOnScreen();
      controller.setCurrentStage(stage);
      int senderId = ConnectionController.getInstance().getIdPlayer();
      ConnectionController.getInstance().send(new CreateGameMessage(senderId, usuarioLogueado));

    } catch (Exception ex) {
      GestorLogs.registrarException(ex);
    }
  }
  @FXML
  void processJoinGame(ActionEvent event) {
    GestorLogs.registrarLog("Creando nuevo Juego...");
    String fxml = ConstantesFXML.FXML_UNIRME_JUEGO;

    try {
      Parent root;
      Stage stage = new Stage();
      FXMLLoader loader = ScreensFramework.getLoader(fxml);

      root = (Parent) loader.load();
      UnirmeJuegoController controller = (UnirmeJuegoController) loader.getController();
      controller.setPrevStage(currentStage);
      controller.setUsuarioLogueado(usuarioLogueado);

      Scene scene = new Scene(root);
      stage.setScene(scene);
      stage.setTitle("Monopoly - Unirme a Juego");
      stage.centerOnScreen();
      controller.setCurrentStage(stage);
      // int senderId = ConnectionController.getInstance().getIdPlayer();
      // ConnectionController.getInstance().send(new
      // JoinGameMessage(senderId, usuarioLogueado));
      ConnectionController.getInstance().send(ConstantesMensaje.GET_PENDING_GAMES_MESSAGE);

    } catch (Exception ex) {
      GestorLogs.registrarException(ex);
    }
  }
 private void configPopUpWindow(Stage popUpStage) {
   Image icono =
       new Image(getClass().getResourceAsStream("/Resources/Images/Icons/settingIcon.png"));
   popUpStage.getIcons().add(icono);
   popUpStage.setTitle("Opciones de la partida");
   popUpStage.centerOnScreen();
   popUpStage.setResizable(false);
 }
예제 #4
0
 @SuppressWarnings("unused")
 public static void mostrarLogin() {
   LoginController loginController = new LoginController();
   BDevMain.getPrimaryStage()
       .getScene()
       .getStylesheets()
       .add(BDevMain.class.getResource(BDev.getPropiedad("genericos.rutaCSS")).toExternalForm());
   primaryStage.show();
   primaryStage.centerOnScreen();
 }
예제 #5
0
  public static void mostrarMenuPrincipal() {
    MenuController menuController = new MenuController();
    menuBorderView = menuController.getView();

    BDevMain.getPrimaryStage()
        .getScene()
        .getStylesheets()
        .add(BDevMain.class.getResource(BDev.getPropiedad("genericos.rutaCSS")).toExternalForm());

    primaryStage.centerOnScreen();

    BDevMain.mostrarMensaje(
        String.format(
            "¡Bienvenido %s!", BDev.obtenerNombreUsuario(BDev.getSesionBean().getUsuarioBean())));
  }
  public void showOptionMenu(Parent root) {
    GestorLogs.registrarLog("Desplegar Menú de Opciones..");

    try {
      currentStage = new Stage();

      Scene scene = new Scene(root);
      currentStage.setScene(scene);
      currentStage.setTitle("Monopoly - Menú de Opciones");
      currentStage.centerOnScreen();
      currentStage.setResizable(false);
      prevStage.close();
      currentStage.show();

    } catch (Exception ex) {
      GestorLogs.registrarException(ex);
    }
  }
  @FXML
  private void volverMenuPrincipal(ActionEvent event) {

    try {
      // Cargamos la scene
      FXMLLoader loader = new FXMLLoader();
      loader.setLocation(Principal.class.getResource("MenuGerente.fxml"));
      AnchorPane Gerente = (AnchorPane) loader.load();

      // Agregamos a la ventana
      Scene scene = new Scene(Gerente);
      Node node = (Node) event.getSource();
      Stage primaryStage = (Stage) node.getScene().getWindow();
      primaryStage.setScene(scene);
      primaryStage.centerOnScreen();
      primaryStage.setTitle("Menu Gerente");
      primaryStage.show();

    } catch (IOException e) {
    }
  }
예제 #8
0
파일: StageApp.java 프로젝트: zxiaofan/JDK
  public Parent createContent() {

    // create a button for initializing our new stage
    Button button = new Button("Create a Stage");
    button.setStyle("-fx-font-size: 24;");
    button.setDefaultButton(true);
    button.setOnAction(
        (ActionEvent t) -> {
          final Stage stage = new Stage();

          // create root node of scene, i.e. group
          Group rootGroup = new Group();

          // create scene with set width, height and color
          Scene scene = new Scene(rootGroup, 200, 200, Color.WHITESMOKE);

          // set scene to stage
          stage.setScene(scene);

          // set title to stage
          stage.setTitle("New stage");

          // center stage on screen
          stage.centerOnScreen();

          // show the stage
          stage.show();

          // add some node to scene
          Text text = new Text(20, 110, "JavaFX");
          text.setFill(Color.DODGERBLUE);
          text.setEffect(new Lighting());
          text.setFont(Font.font(Font.getDefault().getFamily(), 50));

          // add text to the main root group
          rootGroup.getChildren().add(text);
        });
    return button;
  }
  /** Entry point for the JavaFX application. Configure & show the stage. */
  @Override
  public void start(Stage primaryStage) {

    primaryStage.setTitle("CSSem - Lambda Expression Examples");

    primaryStage.setMinWidth(JavaFXClass.MIN_WIDTH);
    primaryStage.setMaxWidth(JavaFXClass.MAX_WIDTH);
    primaryStage.setMinHeight(JavaFXClass.MIN_HEIGHT);
    primaryStage.setMaxHeight(JavaFXClass.MAX_HEIGHT);

    primaryStage.setScene(new Scene(this.layout));

    Runnable stageResized =
        () -> this.stageResized(primaryStage.getWidth(), primaryStage.getHeight());
    ChangeListener<? super Number> widthHeightListener = (v, o, n) -> stageResized.run();
    primaryStage.widthProperty().addListener(widthHeightListener);
    primaryStage.heightProperty().addListener(widthHeightListener);

    primaryStage.show();
    primaryStage.centerOnScreen();
    stageResized.run();
  }
예제 #10
0
  @Override
  public void start(final Stage primaryStage) {
    primaryStage.setTitle("Chapter 3-2 Playing Video");
    primaryStage.centerOnScreen();
    primaryStage.initStyle(StageStyle.TRANSPARENT);

    final Group root = new Group();
    final Scene scene = new Scene(root, 540, 300, Color.rgb(0, 0, 0, 0));

    // rounded rectangle with slightly transparent
    Node applicationArea = createBackground(scene);
    root.getChildren().add(applicationArea);

    // allow the user to drag window on the desktop
    attachMouseEvents(scene, primaryStage);

    // allows the user to see the progress of the video playing
    progressSlider = createSlider(scene);
    root.getChildren().add(progressSlider);

    // Dragging over surface
    scene.setOnDragOver(
        new EventHandler<DragEvent>() {
          @Override
          public void handle(DragEvent event) {
            Dragboard db = event.getDragboard();
            if (db.hasFiles() || db.hasUrl() || db.hasString()) {
              event.acceptTransferModes(TransferMode.COPY);
              if (mediaPlayer != null) {
                mediaPlayer.stop();
              }
            } else {
              event.consume();
            }
          }
        });

    // update slider as video is progressing (later removal)
    progressListener =
        new ChangeListener<Duration>() {
          public void changed(
              ObservableValue<? extends Duration> observable,
              Duration oldValue,
              Duration newValue) {
            progressSlider.setValue(newValue.toSeconds());
          }
        };

    // Dropping over surface
    scene.setOnDragDropped(
        new EventHandler<DragEvent>() {

          @Override
          public void handle(DragEvent event) {
            Dragboard db = event.getDragboard();
            boolean success = false;
            URI resourceUrlOrFile = null;

            // dragged from web browser address line?
            if (db.hasContent(DataFormat.URL)) {
              try {
                resourceUrlOrFile = new URI(db.getUrl().toString());
              } catch (URISyntaxException ex) {
                ex.printStackTrace();
              }
            } else if (db.hasFiles()) {
              // dragged from the file system
              String filePath = null;
              for (File file : db.getFiles()) {
                filePath = file.getAbsolutePath();
              }
              resourceUrlOrFile = new File(filePath).toURI();
              success = true;
            }
            // load media
            Media media = new Media(resourceUrlOrFile.toString());

            // stop previous media player and clean up
            if (mediaPlayer != null) {
              mediaPlayer.stop();
              mediaPlayer.currentTimeProperty().removeListener(progressListener);
              mediaPlayer.setOnPaused(null);
              mediaPlayer.setOnPlaying(null);
              mediaPlayer.setOnReady(null);
            }

            // create a new media player
            mediaPlayer = MediaPlayerBuilder.create().media(media).build();

            // as the media is playing move the slider for progress
            mediaPlayer.currentTimeProperty().addListener(progressListener);

            // play video when ready status
            mediaPlayer.setOnReady(
                new Runnable() {
                  @Override
                  public void run() {
                    progressSlider.setValue(1);
                    progressSlider.setMax(mediaPlayer.getMedia().getDuration().toMillis() / 1000);
                    mediaPlayer.play();
                  }
                });

            // Lazy init media viewer
            if (mediaView == null) {
              mediaView =
                  MediaViewBuilder.create()
                      .mediaPlayer(mediaPlayer)
                      .x(4)
                      .y(4)
                      .preserveRatio(true)
                      .opacity(.85)
                      .smooth(true)
                      .build();

              mediaView.fitWidthProperty().bind(scene.widthProperty().subtract(220));
              mediaView.fitHeightProperty().bind(scene.heightProperty().subtract(30));

              // make media view as the second node on the scene.
              root.getChildren().add(1, mediaView);
            }

            // sometimes loading errors occur
            mediaView.setOnError(
                new EventHandler<MediaErrorEvent>() {
                  public void handle(MediaErrorEvent event) {
                    event.getMediaError().printStackTrace();
                  }
                });

            mediaView.setMediaPlayer(mediaPlayer);

            event.setDropCompleted(success);
            event.consume();
          }
        });

    // rectangular area holding buttons
    final Group buttonArea = createButtonArea(scene);

    // stop button will stop and rewind the media
    Node stopButton = createStopControl();

    // play button can resume or start a media
    final Node playButton = createPlayControl();

    // pauses media play
    final Node pauseButton = createPauseControl();

    stopButton.setOnMousePressed(
        new EventHandler<MouseEvent>() {
          public void handle(MouseEvent me) {
            if (mediaPlayer != null) {
              buttonArea.getChildren().removeAll(pauseButton, playButton);
              buttonArea.getChildren().add(playButton);
              mediaPlayer.stop();
            }
          }
        });
    // pause media and swap button with play button
    pauseButton.setOnMousePressed(
        new EventHandler<MouseEvent>() {
          public void handle(MouseEvent me) {
            if (mediaPlayer != null) {
              buttonArea.getChildren().removeAll(pauseButton, playButton);
              buttonArea.getChildren().add(playButton);
              mediaPlayer.pause();
              paused = true;
            }
          }
        });

    // play media and swap button with pause button
    playButton.setOnMousePressed(
        new EventHandler<MouseEvent>() {
          public void handle(MouseEvent me) {
            if (mediaPlayer != null) {
              buttonArea.getChildren().removeAll(pauseButton, playButton);
              buttonArea.getChildren().add(pauseButton);
              paused = false;
              mediaPlayer.play();
            }
          }
        });

    // add stop button to button area
    buttonArea.getChildren().add(stopButton);

    // set pause button as default
    buttonArea.getChildren().add(pauseButton);

    // add buttons
    root.getChildren().add(buttonArea);

    // create a close button
    Node closeButton = createCloseButton(scene);
    root.getChildren().add(closeButton);

    primaryStage.setOnShown(
        new EventHandler<WindowEvent>() {
          public void handle(WindowEvent we) {
            previousLocation = new Point2D(primaryStage.getX(), primaryStage.getY());
          }
        });

    primaryStage.setScene(scene);
    primaryStage.show();
  }
예제 #11
0
  @Override
  public void start(Stage theStage) {
    this.tStage = theStage;
    theStage.setTitle("Ball of Duty");
    theStage.setHeight(WINDOW_START_HEIGHT);
    theStage.setWidth(WINDOW_START_WIDTH);
    theStage.centerOnScreen();
    theStage.setResizable(false);
    theStage.setOnCloseRequest(
        new EventHandler<WindowEvent>() {
          public void handle(WindowEvent we) {
            gameManager.quitGame();
            System.exit(0);
          }
        });

    BorderPane startMenuRoot = new BorderPane();
    startMenu = new Scene(startMenuRoot);

    gameBox = new BorderPane();
    Scene gameScene = new Scene(gameBox);

    BorderPane createAccountRoot = new BorderPane();
    BorderPane lohInRoot = new BorderPane();

    theStage.setScene(startMenu);

    gameManager = new GameClient(getRelativeSceneLocation(theStage));

    scale = new Scale();
    scale.xProperty().bind(gameScene.widthProperty().divide(WINDOW_START_WIDTH));
    scale.yProperty().bind(gameScene.heightProperty().divide(WINDOW_START_HEIGHT));
    scale.setPivotX(0);
    scale.setPivotY(0);
    // gameBox.getTransforms().add(scale);
    // gameBox.setBackground(null);
    // TODO scaling

    theStage
        .heightProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage)); // This
              // only
              // happens
              // once
              // for
              // some
              // reason.
            });
    theStage
        .widthProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    theStage
        .xProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    theStage
        .yProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    gameScene
        .xProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    gameScene
        .yProperty()
        .addListener(
            e -> {
              gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
            });
    Image image = new Image("images/frontpage.png");
    BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, false);
    // new BackgroundImage(image, repeatX, repeatY, position, size)
    BackgroundImage backgroundImage =
        new BackgroundImage(
            image,
            BackgroundRepeat.REPEAT,
            BackgroundRepeat.NO_REPEAT,
            BackgroundPosition.CENTER,
            backgroundSize);
    // new Background(images...)
    Background background = new Background(backgroundImage);
    startMenuRoot.setBackground(background);

    RadioButton chooseBlaster = new RadioButton("Blaster");
    RadioButton chooseRoller = new RadioButton("Roller");
    RadioButton chooseHeavy = new RadioButton("Heavy");

    final ToggleGroup specializationGroup = new ToggleGroup();

    chooseBlaster.setToggleGroup(specializationGroup);
    chooseRoller.setToggleGroup(specializationGroup);
    chooseHeavy.setToggleGroup(specializationGroup);

    chooseBlaster.setSelected(true);

    HBox specializationBox = new HBox();
    specializationBox.setSpacing(9);
    specializationBox.getChildren().add(chooseBlaster);
    specializationBox.getChildren().add(chooseRoller);
    specializationBox.getChildren().add(chooseHeavy);

    Label lblNickname = new Label("Nickname:");
    TextField tfNickname = new TextField();
    Button loginStart = new Button("Log in");
    Button createStart = new Button("Create Account");
    theStage.getIcons().add(new Image("images/ball_red.png"));
    VBox mainButtonBox = new VBox();
    mainButtonBox.setSpacing(5);
    Button joinBtn = new Button("Join game");

    Button viewLB = new Button("Leaderboard");
    viewLB.setPrefSize(150, 50);
    viewLB.setId("viewLB");
    viewLB.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

    BorderPane lbBorder = new BorderPane();
    VBox lbBox = new VBox();
    Scene lbScene = new Scene(lbBorder);

    Button lbBack = new Button("Start menu");
    lbBox.getChildren().add(lbBack);
    lbBorder.setLeft(lbBox);
    lbBack.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

    Label topText = new Label("Only shows scores higher than 100!");
    topText.setStyle("-fx-font-size: 20pt;-fx-font-family: Segoe UI Semibold;");

    viewLB.setOnAction(
        ActionEvent -> {
          HighscoreLeaderboard hBoard = gameManager.getHighscoreLeaderboard();
          hBoard.setFocusTraversable(false);
          lbBorder.setCenter(hBoard);
          if (gameManager.getPlayer() != null) {
            Player client = gameManager.getPlayer();
            Label you =
                new Label(
                    "YOU:    "
                        + client.getNickname()
                        + " ["
                        + client.getId()
                        + "]    | Score: "
                        + client.getHighscore());

            you.setStyle("-fx-font-size: 15pt;-fx-font-family: Segoe UI Semibold;");
            lbBorder.setBottom(you);
          }

          BorderPane.setMargin(hBoard, new Insets(12, 12, 12, 12));

          lbBorder.setTop(topText);
          theStage.setScene(lbScene);

          lbBack.setOnAction(
              ActionEvent1 -> {
                theStage.setScene(startMenu);
                startMenuRoot.setLeft(mainButtonBox);

                BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));
              });
        });

    joinBtn.setPrefSize(150, 50);
    tfNickname.setPrefSize(150, 20);
    joinBtn.setId("joinBtn");
    joinBtn.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
    lblNickname.setId("lblNickname");
    lblNickname.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
    createStart.setId("CreateStart");
    createStart.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
    loginStart.setId("loginStart");
    loginStart.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

    joinBtn.setOnAction(
        ActionEvent -> {
          Specializations spec;
          if (chooseRoller.isSelected()) {
            spec = Specializations.ROLLER;
          } else if (chooseHeavy.isSelected()) {
            spec = Specializations.HEAVY;
          } else // Blaster is default, if something goes wrong with radio
          // buttons
          {
            spec = Specializations.BLASTER;
          }

          theStage.setScene(gameScene);
          gameManager.joinAsGuest(gameBox, tfNickname.getText(), spec);
          gameManager.getMap().addObserver(this);
          gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
          gameBox.requestFocus();
        });
    tfNickname.setOnAction(
        ActionEvent -> {
          Specializations spec;
          if (chooseRoller.isSelected()) {
            spec = Specializations.ROLLER;
          } else if (chooseHeavy.isSelected()) {
            spec = Specializations.HEAVY;
          } else // Blaster is default, if something goes wrong with radio
          // buttons
          {
            spec = Specializations.BLASTER;
          }
          theStage.setScene(gameScene);
          gameManager.joinAsGuest(gameBox, tfNickname.getText(), spec);
          gameManager.setSceneRelativeLocation(getRelativeSceneLocation(theStage));
          gameBox.requestFocus();
        });

    mainButtonBox.getChildren().add(lblNickname);
    mainButtonBox.getChildren().add(tfNickname);
    mainButtonBox.getChildren().add(specializationBox);
    mainButtonBox.getChildren().add(joinBtn);
    mainButtonBox.getChildren().add(loginStart);
    mainButtonBox.getChildren().add(createStart);
    mainButtonBox.getChildren().add(viewLB);
    startMenuRoot.setLeft(mainButtonBox);

    createStart.setOnAction(
        ActionEvent -> {
          VBox createAccountButtonBox = new VBox();
          Label lblNickname2 = new Label("Nickname:");
          TextField tfNickname2 = new TextField();
          Label lblUserName = new Label("Name:");
          TextField tfUserName = new TextField();
          Label lblPassword = new Label("Password:"******"Repeat password:"******"Create account");
          Button back = new Button("Start menu");

          createBtn.setId("join-yyyyy");
          createBtn.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          lblUserName.setId("join-game");
          lblUserName.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          lblPassword.setId("join-game");
          lblPassword.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          lblPassword2.setId("join-game");
          lblPassword2.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          back.setId("join-game");
          back.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

          createAccountButtonBox.getChildren().add(lblNickname2);
          createAccountButtonBox.getChildren().add(tfNickname2);
          createAccountButtonBox.getChildren().add(lblUserName);
          createAccountButtonBox.getChildren().add(tfUserName);
          createAccountButtonBox.getChildren().add(lblPassword);
          createAccountButtonBox.getChildren().add(pf);
          createAccountButtonBox.getChildren().add(lblPassword2);
          createAccountButtonBox.getChildren().add(pf2);
          createAccountButtonBox.getChildren().add(createBtn);
          createAccountButtonBox.getChildren().add(back);

          startMenuRoot.setLeft(createAccountButtonBox);
          BorderPane.setMargin(createAccountButtonBox, new Insets(350, 0, 0, 150));

          createBtn.setOnAction(
              ActionEvent1 -> {
                gameManager.createAccount(
                    tfUserName.getText(),
                    tfNickname2.getText(),
                    pf.getText().toCharArray(),
                    pf2.getText().toCharArray());
                startMenuRoot.setLeft(mainButtonBox);
                BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));
              });

          back.setOnAction(
              ActionEvent1 -> {
                startMenuRoot.setLeft(mainButtonBox);
                BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));
              });
        });

    loginStart.setOnAction(
        ActionEvent -> {
          VBox loginButtonBox = new VBox();
          Button logInBtn = new Button("Log in");
          Label lblUserName2 = new Label("Name:");
          TextField tfUserName2 = new TextField();
          Label lblPassword2 = new Label("Password:"******"Start Menu");

          logInBtn.setId("join-game");
          logInBtn.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");
          back2.setId("join-game");
          back2.setStyle("-fx-font: 20 arial; -fx-base: #ff0717;");

          loginButtonBox.getChildren().add(lblUserName2);
          loginButtonBox.getChildren().add(tfUserName2);
          loginButtonBox.getChildren().add(lblPassword2);
          loginButtonBox.getChildren().add(pf3);
          loginButtonBox.getChildren().add(logInBtn);
          loginButtonBox.getChildren().add(back2);

          startMenuRoot.setLeft(loginButtonBox);
          BorderPane.setMargin(loginButtonBox, new Insets(350, 0, 0, 150));

          logInBtn.setOnAction(
              ActionEvent1 -> {
                // TODO login
              });

          back2.setOnAction(
              ActionEvent1 -> {
                startMenuRoot.setLeft(mainButtonBox);
                BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));
              });
        });

    BorderPane.setMargin(mainButtonBox, new Insets(350, 0, 0, 150));

    Button quitBtn = new Button("Quit game");
    quitBtn.setPrefSize(80, 40);
    quitBtn.setId("quit-game");

    quitBtn.setOnAction(
        ActionEvent -> {
          gameManager.quitGame();
          theStage.setScene(startMenu);
        });

    canvas = new Canvas(CANVAS_START_WIDTH, CANVAS_START_HEIGHT);
    gameBox.setCenter(canvas);
    BorderPane.setAlignment(canvas, Pos.TOP_LEFT);

    gameBox.setBottom(quitBtn);
    BorderPane.setAlignment(quitBtn, Pos.TOP_LEFT);
    theStage.show();
  }
예제 #12
0
    @Override
    public void start(final Stage stage) throws Exception {
      File workingDir = new File(System.getProperty("loadui.working", ".")).getAbsoluteFile();
      Scene splashScene;
      try {
        splashScene =
            FXMLLoader.load(new File(workingDir, "res/loadui-splash.fxml").toURI().toURL());
      } catch (IOException e) {
        splashScene =
            SceneBuilder.create()
                .width(600)
                .height(320)
                .fill(Color.DARKGRAY)
                .root(LabelBuilder.create().text(System.getProperty(LOADUI_NAME, "loadUI")).build())
                .build();
      }

      Image[] icons = new Image[0];
      try {
        icons =
            new Image[] {
              new Image(new File(workingDir, "res/icon_64x64.png").toURI().toURL().toString()),
              new Image(new File(workingDir, "res/icon_32x32.png").toURI().toURL().toString())
            };
      } catch (Exception e) {
        // e.printStackTrace();
      }

      final String noFx = getParameters().getNamed().get(NOFX_OPTION);
      final String agent = getParameters().getNamed().get("agent");

      if ("true".equals(agent)) setDefaultSystemProperty("loadui.instance", "agent");

      if ("false".equals(noFx)) {
        setDefaultSystemProperty("loadui.headless", "false");
        final Stage splash =
            StageBuilder.create()
                .style(StageStyle.TRANSPARENT)
                .scene(splashScene)
                .icons(icons)
                .build();
        splash.initModality(Modality.APPLICATION_MODAL);
        splash.centerOnScreen();
        splash.show();
        splash.toFront();

        stage.getIcons().addAll(icons);
        stage.setOnShown(
            new EventHandler<WindowEvent>() {
              @Override
              public void handle(WindowEvent event) {
                System.out.println("closing splash!");
                splash.close();
              }
            });
      }

      System.out.println("start called!");

      Task<Void> task =
          new Task<Void>() {
            @Override
            protected Void call() throws Exception {
              System.setSecurityManager(null);

              System.out.println("LoadUIFXLauncher: Creating launcher");
              launcher = createLauncher(getParameters().getRaw().toArray(new String[0]));
              System.out.println("LoadUIFXLauncher: Initializing launcher");
              launcher.init();
              System.out.println("LoadUIFXLauncher: Starting launcher");
              launcher.start();

              if ("false".equals(noFx)) {
                launcher
                    .framework
                    .getBundleContext()
                    .registerService(Stage.class, stage, new Hashtable<String, Object>());
              }
              return null;
            }
          };

      new Thread(task).start();
    }
 /**
  * Goes back to the previous screen (Choose mode screen)
  *
  * @param stage the stage which will display the screen
  * @throws Exception
  */
 private void goBack(Stage stage) throws Exception {
   StartUpController.getInstance().goToChooseModeScreen(stage);
   stage.centerOnScreen();
   stage.setResizable(false);
 }
  /**
   * Draws the MapMaker screen and displays it to the user
   *
   * @param primaryStage the stage to show it in
   * @throws Exception
   */
  public void drawScreen(Stage primaryStage) throws Exception {
    // Create the base BorderPane for the whole window
    BorderPane borderPane = new BorderPane();
    borderPane.setStyle("-fx-background-color: papayawhip");

    // Add some instructions to the user
    String text =
        "Instructions:\n"
            + "1. Click on the map component that you would like to place in the map\n"
            + "2. Click on the place in the map where you want to place the component\n"
            + "3. Repeat until you built the map you want!\n"
            + "4. Hit the 'Save' button when you are done";
    Label instructions = new Label(text);
    instructions.setFont(Font.font("Arial", FontWeight.BOLD, 12));
    instructions.setPadding(new Insets(5, 5, 5, 5));
    borderPane.setTop(instructions);

    // Create the blank Map
    Pane mapPane = new Pane();
    Map map = new Map(width, height);
    MapGridGUIDecorator mapGridGUIDecorator = new MapGridGUIDecorator(map.getGrid());
    ResizeFactor rf = ResizeFactor.getSuggestedResizeFactor(width, height);
    mapGridGUIDecorator.setResizeFactor(rf);
    GridPane mapGridPane = mapGridGUIDecorator.drawComponents();
    mapGridPane.setPadding(new Insets(0, 0, 5, 5));
    mapPane.getChildren().add(mapGridPane);
    borderPane.setCenter(mapPane);
    MapMakerController.setCurrentFocused(ComponentType.NOTHING);

    VBox sideComponents = new VBox();

    /* Add "Components" label */
    Label componentsLabel = new Label("Components");
    componentsLabel.setFont(Font.font("Arial", FontWeight.EXTRA_BOLD, 14));
    componentsLabel.setPadding(new Insets(15, 5, 0, 20));
    sideComponents.getChildren().add(componentsLabel);

    /* Add Intersection square image */
    VBox intersectionPane = new VBox();
    Label intersectionLabel = new Label("Intersection");
    intersectionLabel.setPadding(new Insets(5, 5, 0, 30));
    intersectionLabel.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 12));
    Image intersectionImg = new Image("IntersectionX.png", 60, 60, true, false);
    intersectionImgView = new ImageView(intersectionImg);
    StackPane intersectionStackPane = new StackPane(intersectionImgView);
    intersectionStackPane.setPadding(new Insets(0, 10, 10, 10));
    intersectionPane.getChildren().add(intersectionLabel);
    intersectionPane.getChildren().add(intersectionStackPane);
    sideComponents.getChildren().add(intersectionPane);

    /* Add RoadNS square image */
    VBox roadNSPane = new VBox();
    Label roadNSLabel = new Label("Road (North-South)");
    roadNSLabel.setPadding(new Insets(5, 5, 0, 15));
    roadNSLabel.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 12));
    Image roadNSImg = new Image("RoadBackgroundNS.png", 60, 60, true, false);
    roadNSImgView = new ImageView(roadNSImg);
    StackPane roadNSStackPane = new StackPane(roadNSImgView);
    roadNSStackPane.setPadding(new Insets(0, 10, 10, 10));
    roadNSPane.getChildren().add(roadNSLabel);
    roadNSPane.getChildren().add(roadNSStackPane);
    sideComponents.getChildren().add(roadNSPane);

    /* Add RoadEW square image */
    VBox roadEWPane = new VBox();
    Label roadEWLabel = new Label("Road (East-West)");
    roadEWLabel.setPadding(new Insets(5, 5, 0, 15));
    roadEWLabel.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 12));
    Image roadEWImg = new Image("RoadBackgroundEW.png", 60, 60, true, false);
    roadEWImgView = new ImageView(roadEWImg);
    StackPane roadEWStackPane = new StackPane(roadEWImgView);
    roadEWStackPane.setPadding(new Insets(0, 10, 10, 10));
    roadEWPane.getChildren().add(roadEWLabel);
    roadEWPane.getChildren().add(roadEWStackPane);
    sideComponents.getChildren().add(roadEWPane);

    /* Add Grass square image to empty out cells */
    VBox grassPane = new VBox();
    Label grassLabel = new Label("Grass (clear square)");
    grassLabel.setPadding(new Insets(5, 5, 0, 15));
    grassLabel.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 12));
    Image grassImg = new Image("Grass.png", 60, 60, true, false);
    grassImgView = new ImageView(grassImg);
    StackPane grassStackPane = new StackPane(grassImgView);
    grassStackPane.setPadding(new Insets(0, 10, 10, 10));
    grassPane.getChildren().add(grassLabel);
    grassPane.getChildren().add(grassStackPane);
    sideComponents.getChildren().add(grassPane);

    /* Add Save, Reset buttons */
    VBox buttonsPane = new VBox();
    buttonsPane.setPadding(new Insets(0, 0, 0, 10));
    Label toolsLabel = new Label("Tools");
    toolsLabel.setFont(Font.font("Arial", FontWeight.EXTRA_BOLD, 14));
    toolsLabel.setPadding(new Insets(15, 5, 5, 35));
    buttonsPane.getChildren().add(toolsLabel);
    Insets padding = new Insets(0, 0, 5, 0);
    Button saveButton = new Button("Save Map");
    StackPane saveButtonPane = new StackPane(saveButton);
    saveButtonPane.setPadding(padding);
    saveButton.setStyle("-fx-base:Gold");
    saveButton.setFont(Font.font("System Bold Italic", FontWeight.BOLD, 13));
    buttonsPane.getChildren().add(saveButtonPane);
    Button resetButton = new Button("Reset Map");
    resetButton.setStyle("-fx-base:Gold");
    resetButton.setFont(Font.font("System Bold Italic", FontWeight.BOLD, 13));
    StackPane resetButtonPane = new StackPane(resetButton);
    resetButtonPane.setPadding(padding);
    buttonsPane.getChildren().add(resetButtonPane);
    Button backButton = new Button("Go Back");
    backButton.setStyle("-fx-base:Gold");
    backButton.setFont(Font.font("System Bold Italic", FontWeight.BOLD, 13));
    StackPane backButtonPane = new StackPane(backButton);
    backButtonPane.setPadding(padding);
    buttonsPane.getChildren().add(backButtonPane);

    sideComponents.getChildren().add(buttonsPane);

    Ticker.start();

    /* Add click processing for Map grid squares */
    for (int i = 0; i < height; i++) {
      for (int j = 0; j < width; j++) {
        Node current = getNodeFromIndex(i, j, mapGridPane);
        final int x = j;
        final int y = i;
        current.setOnMouseClicked(
            (MouseEvent click) -> {
              MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
              MapMakerController.setCurrentFocused(ComponentType.MAP_SQUARE);
              current.requestFocus();
            });
        current
            .focusedProperty()
            .addListener(
                (ObservableValue<? extends Boolean> observable,
                    Boolean oldValue,
                    Boolean newValue) -> {
                  ComponentType previous = MapMakerController.getPreviousFocused();
                  if (previous == ComponentType.INTERSECTION) {
                    addIntersection(
                        x, y, map, mapGridGUIDecorator, mapGridPane, intersectionImgView);
                  } else if (previous == ComponentType.ROADNS) {
                    addRoadNS(x, y, map, mapGridGUIDecorator, mapGridPane, roadNSImgView);
                  } else if (previous == ComponentType.ROADEW) {
                    addRoadEW(x, y, map, mapGridGUIDecorator, mapGridPane, roadEWImgView);
                  } else if (previous == ComponentType.GRASS) {
                    addGrass(x, y, map, mapGridGUIDecorator, mapGridPane, grassImgView);
                  }
                });
      }
    }

    /* Add intersection icon click processing */
    DropShadow ds = new DropShadow(15, Color.BLUE);
    intersectionImgView.setOnMouseClicked(
        click -> {
          MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
          MapMakerController.setCurrentFocused(ComponentType.INTERSECTION);
          intersectionImgView.requestFocus();
        });
    intersectionImgView
        .focusedProperty()
        .addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
              if (newValue) intersectionImgView.setEffect(ds);
              else intersectionImgView.setEffect(null);
            });

    /* Add roadNS icon click processing */
    roadNSImgView.setOnMouseClicked(
        click -> {
          MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
          MapMakerController.setCurrentFocused(ComponentType.ROADNS);
          roadNSImgView.requestFocus();
        });
    roadNSImgView
        .focusedProperty()
        .addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
              if (newValue) roadNSImgView.setEffect(ds);
              else roadNSImgView.setEffect(null);
            });

    /* Add roadEW icon click processing */
    roadEWImgView.setOnMouseClicked(
        click -> {
          MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
          MapMakerController.setCurrentFocused(ComponentType.ROADEW);
          roadEWImgView.requestFocus();
        });
    roadEWImgView
        .focusedProperty()
        .addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
              if (newValue) roadEWImgView.setEffect(ds);
              else roadEWImgView.setEffect(null);
            });

    /* Add grass icon click processing */
    grassImgView.setOnMouseClicked(
        click -> {
          MapMakerController.setPreviousFocused(MapMakerController.getCurrentFocused());
          MapMakerController.setCurrentFocused(ComponentType.GRASS);
          grassImgView.requestFocus();
        });
    grassImgView
        .focusedProperty()
        .addListener(
            (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> {
              if (newValue) grassImgView.setEffect(ds);
              else grassImgView.setEffect(null);
            });

    /* Add save button functionality */
    saveButton.setOnMouseClicked(
        click -> {
          TextInputDialog nameDialog = new TextInputDialog();
          nameDialog.setTitle("Save Map");
          nameDialog.setHeaderText(
              "Please provide a name for your map (no spaces or special characters).\nSaved maps go into the /maps directory of your working directory.");
          nameDialog.setContentText("File name");
          Button btOk = (Button) nameDialog.getDialogPane().lookupButton(ButtonType.OK);
          TextField textfield = nameDialog.getEditor();
          Platform.runLater(() -> textfield.requestFocus());
          btOk.setDisable(true);
          textfield
              .textProperty()
              .addListener(
                  ((observable, oldValue, newValue) -> {
                    btOk.setDisable(newValue.trim().isEmpty());
                  }));

          Optional<String> result = nameDialog.showAndWait();
          result.ifPresent(
              name -> {
                name = name.concat(".map");
                try {
                  Map finalMap = buildAndSaveMap(map);
                  finalMap.saveMap(name);
                  goBack(primaryStage);
                } catch (Exception e) {
                  e.printStackTrace();
                }
              });
        });

    resetButton.setOnMouseClicked(
        click -> {
          for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
              Component component = map.getAtLocation(new Coordinate(x, y));
              if (component instanceof Road || component instanceof Intersection) {
                addGrass(x, y, map, mapGridGUIDecorator, mapGridPane, grassImgView);
              }
            }
          }
        });

    backButton.setOnMouseClicked(
        click -> {
          try {
            goBack(primaryStage);
          } catch (Exception e) {
            e.printStackTrace();
          }
        });

    borderPane.setRight(sideComponents);
    Scene scene = new Scene(borderPane);
    primaryStage.setScene(scene);
    primaryStage.centerOnScreen();
    primaryStage.setResizable(false);
  }