@FXML
  private void gameSetup(ActionEvent e) throws NullPointerException {
    try {
      if (e.getSource() == nextButton) {
        numPlayer = Integer.parseInt(numPlayers.getSelectionModel().getSelectedItem().toString());
        // initializing players array
        players = new Player[numPlayer.intValue()];
        String map = mapType.getSelectionModel().getSelectedItem().toString();
        if (Objects.equals(map, "Random")) {
          try {
            gameRoot = FXMLLoader.load(getClass().getResource("UIFiles/MainMap.fxml"));
            //				RandMap.setImages();
          } catch (Exception e1) {
            e1.printStackTrace();
          }
        }
        level =
            difficulty
                .getSelectionModel()
                .getSelectedItem()
                .toString(); // "Beginner", "Standard", or "Tournament"
        Launcher.primaryStage.setScene(
            Launcher.nextScene); // Show player config screen for player 1
        Launcher.primaryStage.setTitle("Player 1 Configuration");
        count = 1;

      } else if (e.getSource() == cancelButton) {
        Launcher.primaryStage.close();
      }
    } catch (NullPointerException error) {
      Launcher.primaryStage.setScene(Launcher.errorMessage);
    }
  }
 /** Action taken on button click Continue. Creates a player or displays an error. */
 @FXML
 public final void confirmChoices() {
   if (textName.getText().isEmpty()) {
     lblWarning.setText("Please enter a name.");
   } else {
     if (playerCount > 0) {
       // Gets the currently picked color
       final String pickedColor = cmbColor.getValue();
       // Create new player
       final Player tempPlayer =
           new Player(textName.getText(), cmbRace.getValue(), cmbColor.getValue());
       main.addPlayer(tempPlayer); // Add new player
       // Remove picked Color from list
       cmbColor.getItems().remove(pickedColor);
       // Sets combo boxes back to zero index
       cmbColor.getSelectionModel().select(0);
       cmbRace.getSelectionModel().select(0);
       textName.clear();
       lblWarning.setText("");
       playerCount--; // Decrement player count after creation
       playerNum++; // Increment player Label number
       lblPlayerNum.setText("Player " + playerNum + ": Choose Your Options");
     } else {
       // If just one player, and end case for last player
       final Player tempPlayer =
           new Player(textName.getText(), cmbRace.getValue(), cmbColor.getValue());
       main.addPlayer(tempPlayer);
       // Display the map Screen to start game
       main.showMapScreen();
     }
   }
 }
  private void updateModelValue() {
    if (property.get() == null || !(property.get() instanceof FromConfigurationPropertyValue)) {
      try {
        String defaultName = (String) choiceBox.getItems().get(0);
        Configuration defaultValue = Registery.get().getConfiguration(defaultName);
        property.set(new FromConfigurationPropertyValue(defaultValue));
      } catch (Exception ex) {
        Logger.getLogger(ConfigurationPropertyEditor.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    FromConfigurationPropertyValue fcpv = (FromConfigurationPropertyValue) property.get();

    if (fcpv != null
        && fcpv.getValue()
            != null) { // in case property is a dummy (came from collection property editor)
      Class implementor = fcpv.getValue().configuredType();
      String className = Registery.get().getRegisteredClassName(implementor);
      Property temp = property;
      property = null;
      choiceBox.getSelectionModel().select(className);
      property = temp;
      if (parentCollection != null && choiceBox.getItems().size() <= 1) {
        setText(className);
      }
      confEditor.setModel(fcpv.getValue(), readOnly, filter);
    } else {
      choiceBox.getSelectionModel().select("NULL");
    }
  }
Exemple #4
0
 public void updateModel(Ledger item) {
   item.setId(Integer.parseInt(transId.getText()));
   item.setAccountNum(
       Integer.parseInt(accountNum.getSelectionModel().getSelectedItem().toString()));
   item.setTransDesc(transDescription.getText());
   item.setAccountNum(
       Integer.parseInt(accountNum.getSelectionModel().getSelectedItem().toString()));
   item.setCheckNum(checkNum.getText());
   item.setTransAmt(Float.parseFloat(transAmt.getText()));
   item.setTransBal(Float.parseFloat(transBalance.getText()));
 }
  /** Init function used by JavaFX. */
  @FXML
  private void initialize() {

    lblPlayerNum.setText("Player 1: Choose Your Options");

    cmbRace.getItems().addAll("Human", "Flapper", "Other");

    cmbColor.getItems().addAll("Blue", "Yellow", "Green", "Orange");

    cmbColor.getSelectionModel().select(0);
    cmbRace.getSelectionModel().select(0);
  }
  public boolean isOkPressed(int typeSignal) {
    ((StageLoader) btnOK.getScene().getWindow()).setMethod(() -> btnOK());
    if (tuSignal == null) return false;
    Stage w = (Stage) btnOK.getScene().getWindow();

    if (typeSignal == 3) {
      List<SpTuCommand> tuCommands =
          SingleFromDB.spTuCommands
              .stream()
              .filter(f -> f.getObjref() == tuSignal.getStateref())
              .collect(Collectors.toList());
      ChoiceBox<SpTuCommand> chBox = new ChoiceBox<>();
      tuCommands.forEach(chBox.getItems()::add);
      chBox
          .getSelectionModel()
          .selectedItemProperty()
          .addListener(
              (observ, oldValue, newValue) -> {
                value = newValue.getVal() + "";
              });
      if (chBox.getItems().size() > 0) chBox.getSelectionModel().selectFirst();
      if (SingleObject.selectedShape.getValueProp().get()
          == chBox.getSelectionModel().getSelectedItem().getVal()) {
        chBox.getSelectionModel().selectNext();
      }
      Platform.runLater(() -> chBox.requestFocus());
      bpTU.setCenter(chBox);
    } else if (typeSignal == 1) {
      TextField txtField = new TextField();
      txtField.setText(SingleObject.selectedShape.getValueProp().get() + "");
      txtField
          .textProperty()
          .addListener(
              (observ, oldValue, newValue) -> {
                try {
                  Double.parseDouble(newValue);
                  value = newValue;
                } catch (Exception e) {
                  txtField.setText(oldValue);
                }
              });
      Platform.runLater(() -> txtField.requestFocus());
      bpTU.setCenter(txtField);
    } else {
      System.out.println("=====   This is not TU or TI   =====");
    }
    w.showAndWait();

    return isOkClicked;
  }
  public FXMesureAreaHandler() {
    super();
    uiArea.setMaxHeight(Double.MAX_VALUE);
    uiUnit.setItems(FXCollections.observableArrayList(Unit.valueOf("km2"), SI.SQUARE_METRE));
    uiUnit.getSelectionModel().selectFirst();

    pane.setAlignment(Pos.CENTER);
    pane.setBackground(
        new Background(new BackgroundFill(Color.WHITE, new CornerRadii(10), Insets.EMPTY)));
    pane.setPadding(new Insets(10, 10, 10, 10));
    deco.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
    deco.getColumnConstraints()
        .add(
            new ColumnConstraints(
                0, HBox.USE_COMPUTED_SIZE, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true));
    deco.getColumnConstraints()
        .add(
            new ColumnConstraints(
                0, HBox.USE_COMPUTED_SIZE, Double.MAX_VALUE, Priority.NEVER, HPos.CENTER, true));
    deco.getColumnConstraints()
        .add(
            new ColumnConstraints(
                0, HBox.USE_COMPUTED_SIZE, Double.MAX_VALUE, Priority.ALWAYS, HPos.CENTER, true));

    uiUnit
        .valueProperty()
        .addListener(
            (ObservableValue<? extends Unit> observable, Unit oldValue, Unit newValue) -> {
              updateGeometry();
            });

    deco.add(pane, 1, 0);
  }
  private void updateDistanceDistributionChart() {

    double[][] transformedTrajectory = getTransformedTrajectory();
    if (transformedTrajectory == null) return;

    double approxDiameter =
        PhaseSpaceDistribution.maxPhaseSpaceDiameterApproximate(transformedTrajectory);

    long[] histo;
    // subsequent distance distribution
    if (distanceDistributionSelector.getSelectionModel().getSelectedIndex() == 0) {
      histo =
          PhaseSpaceDistribution.approximateSubsequentDistanceDistribution(
              transformedTrajectory, 1500, approxDiameter);
    } else {
      histo =
          PhaseSpaceDistribution.approximateDistanceDistribution(
              transformedTrajectory, 1500, approxDiameter);
    }

    subsequentDistanceDistributionChart.getData().clear();
    XYChart.Series series = new XYChart.Series();
    for (int i = 0; i < histo.length; i++) {
      series.getData().add(new XYChart.Data(i, histo[i]));
    }
    subsequentDistanceDistributionChart.getData().add(series);
  }
 /** {@inheritDoc} */
 @Override
 protected Modello buildEntity() {
   Modello modello = new Modello();
   try {
     if (id != 0) {
       modello.setId(id);
     }
     modello.setTipoCarburante(tipoCarburante.getSelectionModel().getSelectedItem());
     modello.setCapacitàBagagliaio(Integer.parseInt(capacitàBagagliaio.getText()));
     modello.setNumeroPorte(Integer.parseInt(numeroPorte.getText()));
     modello.setMarca(marca.getText());
     modello.setNome(nome.getText());
     modello.setEmissioniCO2(Double.parseDouble(emissioniCO2.getText()));
     modello.setNumeroPosti(Integer.parseInt(numeroPosti.getText()));
     modello.setPotenza(Integer.parseInt(potenza.getText()));
     modello.setPeso(Integer.parseInt(peso.getText()));
     modello.setTrasmissioneAutomatica(trasmissioneAutomatica.selectedProperty().get());
     if (!fascia.getText().isEmpty())
       modello.setFascia((Fascia) controller.processRequest("ReadFascia", fascia.getText()));
     else modello.setFascia(null);
     return modello;
   } catch (Exception e) {
     return null;
   }
 }
Exemple #10
0
 @Override
 public void initialize(final URL url, final ResourceBundle bundle) {
   exitItem.setOnAction(e -> Platform.exit());
   roomSelection.setItems(FXCollections.observableArrayList("arduino", "java", "groovy", "scala"));
   roomSelection.getSelectionModel().select(1);
   model.userName.bindBidirectional(userNameTextfield.textProperty());
   model.roomName.bind(roomSelection.getSelectionModel().selectedItemProperty());
   model.readyToChat.bind(
       model.userName.isNotEmpty().and(roomSelection.selectionModelProperty().isNotNull()));
   chatButton.disableProperty().bind(model.connected.not());
   messageTextField.disableProperty().bind(model.connected.not());
   messageTextField.textProperty().bindBidirectional(model.currentMessage);
   connectButton.disableProperty().bind(model.readyToChat.not());
   chatListView.setItems(model.chatHistory);
   messageTextField.setOnAction(
       event -> {
         handleSendMessage();
       });
   chatButton.setOnAction(
       evt -> {
         handleSendMessage();
       });
   connectButton.setOnAction(
       evt -> {
         try {
           clientEndPoint =
               new ChatClientEndpoint(
                   new URI("ws://quevedo2dam.azurewebsites.net/chat/" + model.roomName.get()));
           clientEndPoint.addMessageHandler(
               responseString -> {
                 Platform.runLater(
                     () -> {
                       model.chatHistory.add(
                           jsonMessageToString(responseString, model.roomName.get()));
                     });
               });
           model.connected.set(true);
         } catch (Exception e) {
           showDialog("Error: " + e.getMessage());
         }
       });
   aboutMenuItem.setOnAction(
       event -> {
         showDialog(
             "Example websocket chat bot written in JavaFX.\n\n Please feel free to visit my blog at www.hascode.com for the full tutorial!\n\n2014 Micha Kops");
       });
 }
 public void handleApply(ActionEvent actionEvent) {
   String method = choiceBox.getValue();
   ImagePane imagePane = toolController.getActivePane();
   CommandManager manager = imagePane.getCommandManager();
   BufferedImage secondImage =
       secondImageChoiceBox.getSelectionModel().getSelectedItem().getImage();
   manager.executeCommand(new BinaryOperationCommand(imagePane, secondImage, method));
   imagePane.setImage(imagePane.getImage());
 }
Exemple #12
0
 public void loadNumberChoiceBox() {
   int nr =
       (Objekte.getMapData().getMapNumberListById(Objekte.getMapData().getCurNumberId())).getNr();
   cb.getItems().clear();
   for (Data.MapNumber mapN : Objekte.getMapData().getMapNumberList()) {
     String anzeige = "";
     anzeige += "" + mapN.getNr() + ": " + mapN.getName();
     cb.getItems().add(anzeige);
   }
   cb.getSelectionModel().select(nr - 1);
 }
 @FXML
 void bestOf() {
   initRankings();
   if (rankings.size() > 0) {
     while (choiceRank < rankings.size()
         && rankings.get(choiceRank).getFirst()
             != category.getSelectionModel().getSelectedItem()) {
       choiceRank += 1;
     }
     updateRanked();
   }
 }
  /** ButtonMethod for add ingredients from the ingredientList into the tableview */
  public void addIngredientButton() {

    String selectedIngredient = recipeIngredients.getSelectionModel().getSelectedItems().toString();
    selectedIngredient = selectedIngredient.replaceAll("\\[", "").replaceAll("\\]", "");

    items.add(
        new Ingredient(
            selectedIngredient,
            ingredientAmount.getText(),
            ingredientUnit.getSelectionModel().getSelectedItem().toString())); // Creates new
    addedIngredientTable.setItems(
        items); // Object of the type Ingredient and adds it to the tableView.
  }
  protected BinaryOperationsTool(ToolController controller) {
    super(controller);
    ResourceBundle bundle = controller.getBundle();
    this.choiceBox = new ChoiceBox<>();
    choiceBox.getItems().addAll(methods);
    choiceBox.getSelectionModel().select(0);

    Separator separator = new Separator(Orientation.HORIZONTAL);
    Label label = new Label(bundle.getString("BinaryOperations"));
    updateChoiceBoxItems();
    secondImageChoiceBox.setOnMouseClicked(event1 -> updateChoiceBoxItems());

    getChildren().addAll(separator, label, choiceBox, secondImageChoiceBox, applyCancelBtns);
  }
  @FXML
  void train() {
    try {
      learner = learners.newInstanceOf(algorithm.getSelectionModel().getSelectedItem());
      BlockingQueue<Duple<Move, AdaptedYUYVImage>> imgs = new ArrayBlockingQueue<>(1);
      startProducerThread(trainingSet.getSelectionModel().getSelectedItem(), imgs);
      label.setTextFill(Color.BLACK);
      label.setText("0");
      startConsumerThread(
          imgs,
          mImg -> {
            Platform.runLater(
                () -> {
                  label.setText(Integer.toString(Integer.parseInt(label.getText()) + 1));
                  learner.train(mImg.getSecond(), mImg.getFirst());
                });
          });

    } catch (InstantiationException e) {
      reportProblem(e);
    } catch (IllegalAccessException e) {
      reportProblem(e);
    }
  }
  @FXML
  void initialize() {
    assert null != gridPane
        : "fx:id=\"gridPane\" was not injected: check your FXML file 'UploadMonetization.fxml'.";
    assert null != monetizeOverlay
        : "fx:id=\"monetizeOverlay\" was not injected: check your FXML file 'UploadMonetization.fxml'.";
    assert null != monetizeProduct
        : "fx:id=\"monetizeProduct\" was not injected: check your FXML file 'UploadMonetization.fxml'.";
    assert null != monetizeSyndication
        : "fx:id=\"monetizeSyndication\" was not injected: check your FXML file 'UploadMonetization.fxml'.";
    assert null != monetizeTrueView
        : "fx:id=\"monetizeTrueView\" was not injected: check your FXML file 'UploadMonetization.fxml'.";

    monetizeSyndication.setItems(syndicationList);
    syndicationList.addAll(Syndication.values());
    monetizeSyndication.getSelectionModel().selectFirst();
  }
  @FXML // This method is called by the FXMLLoader when initialization is complete
  void initialize() {
    assert currentFileName != null
        : "fx:id=\"currentFileName\" was not injected: check your FXML file 'DataImporter.fxml'.";
    assert worksheetSelector != null
        : "fx:id=\"worksheetSelector\" was not injected: check your FXML file 'DataImporter.fxml'.";
    assert contentTable != null
        : "fx:id=\"contentTable\" was not injected: check your FXML file 'DataImporter.fxml'.";
    assert skipFirstSelection != null
        : "fx:id=\"skipFirstSelection\" was not injected: check your FXML file 'DataImporter.fxml'.";

    worksheetSelector.getSelectionModel().selectedItemProperty().addListener(this::changeSheet);
    List<Integer> zeroThroughTen = IntStream.range(0, 10).boxed().collect(Collectors.toList());
    skipFirstSelection.setItems(new ObservableListWrapper<>(zeroThroughTen));
    Platform.runLater(() -> skipFirstSelection.getSelectionModel().selectFirst());

    contentTable.setPlaceholder(new Label(CurlyApp.getMessage(NO_DATA_LOADED)));
  }
  @FXML
  public void decipherButtonClick(ActionEvent event) {
    deOpenLabel.setText("");
    enSaveLabel.setText("");
    switch (choiceBox.getSelectionModel().getSelectedItem()) {
      case "Simple ASCII Cipher":
        textArea.setText(CipherMaker.decipherSimple(textArea.getText()));
        break;
      case "Cesar Chiper":
        textArea.setText(CipherMaker.decipherCesar(textArea.getText()));
        break;
      case "Vigenere":
        if (!textArea.getText().equals("")) {
          TextInputDialog dialog = new TextInputDialog();
          dialog.setTitle("Cipher-Code");
          dialog.setHeaderText("Type in a Password to decipher your text with!");
          dialog.setContentText("Enter your password here...");

          Optional<String> result = dialog.showAndWait();
          if (result.isPresent()) {
            textArea.setText(CipherMaker.decipherVigenere(textArea.getText(), result.get()));
          }
        }
        break;
      case "RC4":
        if (!textArea.getText().equals("")) {
          TextInputDialog dialog = new TextInputDialog();
          dialog.setTitle("Cipher-Code");
          dialog.setHeaderText("Type in the number to decipher!");
          dialog.setContentText("Enter your number here...");

          Optional<String> result = dialog.showAndWait();
          if (result.isPresent() && result.get().matches("[0-9]+")) {
            textArea.setText(
                CipherMaker.decipherRC4(textArea.getText(), Integer.parseInt(result.get())));
          } else {
            deOpenLabel.setText("Decipher not possible...");
          }
        }

        break;
    }
  }
  @FXML
  public void compute() {
    double[][] transformedTrajectory = getTransformedTrajectory();
    if (transformedTrajectory == null) return;

    // compute and display RP
    BufferedImage rp =
        DRQA.getRPImage(
            transformedTrajectory, transformedTrajectory, recurrenceThresholdSlider.getValue());
    rpImageView.setImage(SwingFXUtils.toFXImage(rp, null));
    applyImageScale();

    // compute and display CRT
    DRQA.conditional_ww_limit = Integer.parseInt(crtLimit.getText());
    DRQA.CRT_LOG_SCALE = logScaleCheckBox.isSelected();
    drqa =
        new DRQA(
            transformedTrajectory, transformedTrajectory, recurrenceThresholdSlider.getValue());
    BufferedImage crt = drqa.getCRTImage(DRQA.conditional_ww_limit, drqa.conditional_ww);
    crtImageView.setImage(SwingFXUtils.toFXImage(crt, null));
    String[] stats = drqa.crtStatistics().split("\t");
    crtStats.setText(
        String.format(
            "mean row: %.2f\tmean col: %.2f\ncorrelation: %.2f\nmax row: %s\tmax col: %s\nlocal maxima: %s\nentropy: %.2f",
            Double.parseDouble(stats[0]),
            Double.parseDouble(stats[1]),
            Double.parseDouble(stats[2]),
            stats[3],
            stats[4],
            stats[5],
            Double.parseDouble(stats[6])));

    drqa.computeRQA(2, 2, 2);
    rqaMeasures.setText(drqa.printableString(DRQA.STANDARD_RQA));

    updateTimeSeriesChart();
    updateDistanceDistributionChart();
    updateLineLengthHistogram(
        null, null, lineLengthTypeSelector.getSelectionModel().getSelectedIndex());
  }
 @Override
 public void initialize(URL arg0, ResourceBundle arg1) {
   tipoCarburante.setItems(FXCollections.observableArrayList(TipoCarburante.values()));
   tipoCarburante.getSelectionModel().select(0);
 }
  /**
   * Drop down event gets values of drop down
   *
   * @param actionEvent
   */
  public void changeAdmin(ActionEvent actionEvent) {

    DropDownvalue = dropDown.getSelectionModel().getSelectedItem();
  }
 /**
  * Reset Btn Event Reset all the field
  *
  * @param ae
  */
 @FXML
 public void ResetBtnClick(ActionEvent ae) {
   password.setText("");
   userName.setText("");
   dropDown.getSelectionModel().clearSelection();
 }
  @FXML
  public void saveButtonClick(ActionEvent event) {
    switch (choiceBox.getSelectionModel().getSelectedItem()) {
      case "Simple ASCII Cipher":
        enSaveLabel.setText("Saving not possible...");
        break;
      case "Cesar Chiper":
        choose.setTitle("Save File: ");
        choose.setInitialDirectory(new File(System.getProperty("user.home") + "/Desktop"));
        choose.setSelectedExtensionFilter(new ExtensionFilter("Text Files (*.txt)", "*.txt"));
        choose.getExtensionFilters().add(new ExtensionFilter("Text Files (*.txt)", "*.txt"));
        fileToSave = choose.showSaveDialog(Main.primaryStage);

        try (PrintWriter pwr = new PrintWriter(new PrintStream(fileToSave))) {

          String[] temp = textArea.getText().split("\n");

          for (int i = 0; i < temp.length; i++) {
            pwr.write(temp[i] + System.getProperty("line.separator"));
          }

        } catch (FileNotFoundException e) {

          Alert alert = new Alert(AlertType.ERROR);
          alert.setTitle("File Save Error");
          alert.setHeaderText("Failed to save File");
          alert.setContentText("Please try again!");

          alert.showAndWait();

        } catch (NullPointerException e) {
          // ignore
        }
        break;
      case "Vigenere":
        choose.setTitle("Save File: ");
        choose.setInitialDirectory(new File(System.getProperty("user.home") + "/Desktop"));
        choose.setSelectedExtensionFilter(new ExtensionFilter("Text Files (*.txt)", "*.txt"));
        choose.getExtensionFilters().add(new ExtensionFilter("Text Files (*.txt)", "*.txt"));
        fileToSave = choose.showSaveDialog(Main.primaryStage);

        try (PrintWriter pwr = new PrintWriter(new PrintStream(fileToSave))) {

          String[] temp = textArea.getText().split("\n");

          for (int i = 0; i < temp.length; i++) {
            pwr.write(temp[i] + System.getProperty("line.separator"));
          }

        } catch (FileNotFoundException e) {

          Alert alert = new Alert(AlertType.ERROR);
          alert.setTitle("File Save Error");
          alert.setHeaderText("Failed to save File");
          alert.setContentText("Please try again!");

          alert.showAndWait();

        } catch (NullPointerException e) {
          // ignore
        }
        break;
      case "RC4":
        choose.setTitle("Save File: ");
        choose.setInitialDirectory(new File(System.getProperty("user.home") + "/Desktop"));
        choose.setSelectedExtensionFilter(new ExtensionFilter("Text Files (*.txt)", "*.txt"));
        choose.getExtensionFilters().add(new ExtensionFilter("Text Files (*.txt)", "*.txt"));
        fileToSave = choose.showSaveDialog(Main.primaryStage);

        try (PrintWriter pwr = new PrintWriter(new PrintStream(fileToSave))) {

          String[] temp = textArea.getText().split("\n");

          for (int i = 0; i < temp.length; i++) {
            pwr.write(temp[i] + System.getProperty("line.separator"));
          }

        } catch (FileNotFoundException e) {

          Alert alert = new Alert(AlertType.ERROR);
          alert.setTitle("File Save Error");
          alert.setHeaderText("Failed to save File");
          alert.setContentText("Please try again!");

          alert.showAndWait();

        } catch (NullPointerException e) {
          // ignore
        }
        break;
    }
  }
  @FXML
  public void openButtonClick(ActionEvent event) {
    switch (choiceBox.getSelectionModel().getSelectedItem()) {
      case "Simple ASCII Cipher":
        deOpenLabel.setText("Opening not possible...");
        break;
      case "Cesar Chiper":
        choose.setTitle("Open File: ");
        choose.setInitialDirectory(new File(System.getProperty("user.home") + "/Desktop"));
        choose.setSelectedExtensionFilter(new ExtensionFilter("Text Files (*.txt)", "*.txt"));
        choose.getExtensionFilters().add(new ExtensionFilter("Text Files (*.txt)", "*.txt"));

        try {
          File fileToOpen = choose.showOpenDialog(Main.primaryStage);
          textArea.clear();

          BufferedReader br = new BufferedReader(new FileReader(fileToOpen));

          String test;

          try {

            while ((test = br.readLine()) != null) {
              textArea.setText(textArea.getText() + test + "\n");
            }

            textArea.setText(textArea.getText().trim());

          } finally {
            br.close();
          }

        } catch (FileNotFoundException e2) {

        } catch (IOException e) {

        } catch (NullPointerException e) {

        }
        break;
      case "Vigenere":
        choose.setTitle("Open File: ");
        choose.setInitialDirectory(new File(System.getProperty("user.home") + "/Desktop"));
        choose.setSelectedExtensionFilter(new ExtensionFilter("Text Files (*.txt)", "*.txt"));
        choose.getExtensionFilters().add(new ExtensionFilter("Text Files (*.txt)", "*.txt"));

        try {
          File fileToOpen = choose.showOpenDialog(Main.primaryStage);
          textArea.clear();

          BufferedReader br = new BufferedReader(new FileReader(fileToOpen));

          String test;

          try {

            while ((test = br.readLine()) != null) {
              textArea.setText(textArea.getText() + test + "\n");
            }

            textArea.setText(textArea.getText().trim());

          } finally {
            br.close();
          }

        } catch (FileNotFoundException e2) {

        } catch (IOException e) {

        } catch (NullPointerException e) {

        }
        break;
      case "RC4":
        choose.setTitle("Open File: ");
        choose.setInitialDirectory(new File(System.getProperty("user.home") + "/Desktop"));
        choose.setSelectedExtensionFilter(new ExtensionFilter("Text Files (*.txt)", "*.txt"));
        choose.getExtensionFilters().add(new ExtensionFilter("Text Files (*.txt)", "*.txt"));

        try {
          File fileToOpen = choose.showOpenDialog(Main.primaryStage);
          textArea.clear();

          BufferedReader br = new BufferedReader(new FileReader(fileToOpen));

          String test;

          try {

            while ((test = br.readLine()) != null) {
              textArea.setText(textArea.getText() + test + "\n");
            }

            textArea.setText(textArea.getText().trim());

          } finally {
            br.close();
          }

        } catch (FileNotFoundException e2) {

        } catch (IOException e) {

        } catch (NullPointerException e) {

        }
        break;
    }
  }
  @FXML
  private void playerSetup(ActionEvent e) throws NullPointerException {
    Stage newStage = new Stage();
    // try {
    if (e.getSource() == nextButton2) {

      String name = playerName.getText();
      String race = raceChoice.getSelectionModel().getSelectedItem().toString();
      if (race.length() > 8) {
        race = race.toUpperCase().substring(0, race.indexOf(" "));
      } else {
        race = race.toUpperCase();
      }
      Player.Race r = Player.Race.valueOf(race);

      Color color = colorPick.getValue();

      // creating Player
      Player p = new Player(name, r, color.toString());
      players[count - 1] = p;
      if (players[players.length - 1] != null) {
        // when players array is full, begins game turns
        Turns gameTurns = new Turns(players);
      }

      if (name.equals("")) { // check if player entered a name
        Launcher.primaryStage.setScene(Launcher.errorMessage);
        Launcher.primaryStage.setTitle("Enter name!");
      } else if (playerColors.contains(color)) {
        Launcher.primaryStage.setScene(Launcher.errorMessage);
        Launcher.primaryStage.setTitle("Choose new color!");
      } else {
        playerColors.add(color);
        if (count == 1) { // if only one player config screen has been shown go to player 2
          Launcher.primaryStage.setTitle("Player 2 Configuration");
          Launcher.primaryStage.toFront();
          playerName.clear();
          raceChoice.getSelectionModel().clearSelection();
          colorPick.setValue(Color.WHITE);
          count += 1;
        } else if (count == 2) {
          if (count == numPlayer) { // if user selected only 2 players then show game screen
            Launcher.primaryStage.hide();
            try {
              gameRoot = FXMLLoader.load(getClass().getResource("UIFiles/MainMap.fxml"));
              gameScene = new Scene(gameRoot);
              Parent startWindow =
                  FXMLLoader.load(getClass().getResource("UIFiles/playerStart.fxml"));
              startScene = new Scene(startWindow);
            } catch (Exception e1) {
              e1.printStackTrace();
            }
            newStage.setScene(gameScene);
            newStage.setTitle("Game Screen");
            newStage.show();
            GameController.beginTurn();
            // creates land array
            landPlots = new Land[9][5]; // 5 rows, 9 columns, col = i, row = j
            int count = 0;
            for (int i = 0; i < landPlots.length; i++) {
              for (int j = 0; j < landPlots[0].length; j++) {
                Land newLand = new Land(i, j);
                newLand.setType(landTypes[count]);
                landPlots[i][j] = newLand;
                count++;
              }
            }
          } else { // if user selected more than 2 players, go on to player 3 config
            Launcher.primaryStage.setTitle("Player 3 Configuration");
            Launcher.primaryStage.toFront();
            playerName.clear();
            raceChoice.getSelectionModel().clearSelection();
            colorPick.setValue(Color.WHITE);
            count += 1;
          }

        } else if (count == 3) {
          if (count == numPlayer) {
            Launcher.primaryStage.hide();
            try {
              gameRoot = FXMLLoader.load(getClass().getResource("UIFiles/MainMap.fxml"));
              gameScene = new Scene(gameRoot);
              Parent startWindow =
                  FXMLLoader.load(getClass().getResource("UIFiles/playerStart.fxml"));
              startScene = new Scene(startWindow);
            } catch (Exception e1) {
              e1.printStackTrace();
            }
            newStage.setScene(gameScene);
            newStage.setTitle("Game Screen");
            newStage.show();
            GameController.beginTurn();
            // creates land array
            landPlots = new Land[9][5]; // 5 rows, 9 columns, col = i, row = j
            int count = 0;
            for (int i = 0; i < landPlots.length; i++) {
              for (int j = 0; j < landPlots[0].length; j++) {
                Land newLand = new Land(i, j);
                newLand.setType(landTypes[count]);
                landPlots[i][j] = newLand;
                count++;
              }
            }
          } else {
            Launcher.primaryStage.setTitle("Player 4 Configuration");
            Launcher.primaryStage.toFront();
            playerName.clear();
            raceChoice.getSelectionModel().clearSelection();
            colorPick.setValue(Color.WHITE);
            count += 1;
          }

        } else if (count == 4) {
          Launcher.primaryStage.hide();
          try {
            gameRoot = FXMLLoader.load(getClass().getResource("UIFiles/MainMap.fxml"));
            gameScene = new Scene(gameRoot);
            Parent startWindow =
                FXMLLoader.load(getClass().getResource("UIFiles/playerStart.fxml"));
            startScene = new Scene(startWindow);
          } catch (Exception e1) {
            e1.printStackTrace();
          }

          newStage.setScene(gameScene);
          newStage.setTitle("Game Screen");
          newStage.show();
          GameController.beginTurn();
          // creates land array
          landPlots = new Land[9][5]; // 5 rows, 9 columns, col = i, row = j
          int count = 0;
          for (int i = 0; i < landPlots.length; i++) {
            for (int j = 0; j < landPlots[0].length; j++) {
              Land newLand = new Land(i, j);
              newLand.setType(landTypes[count]);
              landPlots[i][j] = newLand;
              count++;
            }
          }
        }
      }
    } else if (e.getSource() == backButton) {
      playerName.clear();
      raceChoice.getSelectionModel().clearSelection();
      colorPick.setValue(Color.WHITE);
      Launcher.primaryStage.setScene(Launcher.rootScene);
      Launcher.primaryStage.setTitle("M.U.L.E. Game Setup");
    }
    /*} catch (NullPointerException error) {
    	Launcher.primaryStage.setScene(Launcher.errorMessage);
    	Launcher.primaryStage.setTitle("Error!");
    }*/
  }
  @Override
  public void initialize(URL location, ResourceBundle resources) {
    AppController.instance = this;
    this.res = resources;

    ObservableList<String> modeItems =
        FXCollections.observableArrayList(
            Settings.MODE_NEXT, Settings.MODE_RANDOM, Settings.MODE_SAME);
    modeList.setItems(modeItems);
    modeList.getSelectionModel().select(Settings.currentMode);
    modeList
        .valueProperty()
        .addListener(
            (ObservableValue ov, Object oldVal, Object newVal) -> {
              Settings.currentMode = (String) newVal;
            });

    setupPlaylistsView();
    setupPlaylistsContextMenu();

    setupTracksView();

    tracksView.setContextMenu(tracksContextMenu);
    tracksView.setOnContextMenuRequested(
        (ContextMenuEvent evt) -> {
          setupTracksContextMenu();
          evt.consume();
        });
    tracksView
        .getSelectionModel()
        .selectedItemProperty()
        .addListener(
            (ObservableValue observable, Object oldValue, Object newValue) -> {
              Settings.lastTrackId = newValue != null ? ((Track) newValue).getId() : null;
            });

    playlistsView
        .getSelectionModel()
        .selectedItemProperty()
        .addListener(
            (ObservableValue observable, Object oldValue, Object newValue) -> {
              loadSelectedPlaylist();
              Settings.lastPlaylistId = newValue != null ? ((Playlist) newValue).getId() : null;
              searching = false;
              searchText.setText(StringUtils.EMPTY);
            });

    volumeSlider.setCursor(Cursor.HAND);
    volumeSlider
        .valueProperty()
        .addListener(
            (ObservableValue<? extends Number> ov, Number oldVal, Number newVal) -> {
              if (player != null) {
                player.setVolume(newVal.doubleValue());
              }
              Settings.currentVolume = newVal.doubleValue();
              volumeLabel.setText(
                  String.valueOf((int) Math.ceil(newVal.doubleValue() * 100)) + "%");
            });
    volumeSlider.setValue(Settings.currentVolume);

    imagePlay = new ImageView(new Image(getClass().getResourceAsStream("/images/button_play.png")));
    imagePlay.setScaleX(0.40);
    imagePlay.setScaleY(0.40);
    imagePause =
        new ImageView(new Image(getClass().getResourceAsStream("/images/button_pause.png")));
    imagePause.setScaleX(0.5);
    imagePause.setScaleY(0.5);
    imageSettings =
        new ImageView(new Image(getClass().getResourceAsStream("/images/settings.png")));
    imageSettings.setScaleX(0.5);
    imageSettings.setScaleY(0.5);
    imageUpdate = new ImageView(new Image(getClass().getResourceAsStream("/images/refresh.png")));
    imageUpdate.setScaleX(0.5);
    imageUpdate.setScaleY(0.5);
    imageAdd = new ImageView(new Image(getClass().getResourceAsStream("/images/add.png")));
    imageAdd.setScaleX(0.5);
    imageAdd.setScaleY(0.5);
    imageRename = new ImageView(new Image(getClass().getResourceAsStream("/images/rename.png")));
    imageRename.setScaleX(0.5);
    imageRename.setScaleY(0.5);
    imageDelete = new ImageView(new Image(getClass().getResourceAsStream("/images/delete.png")));
    imageDelete.setScaleX(0.5);
    imageDelete.setScaleY(0.5);

    stateButton.setGraphic(imagePlay);
    settingsButton.setGraphic(imageSettings);
    refreshButton.setGraphic(imageUpdate);
    refreshButton.setTooltip(new Tooltip(res.getString("tooltip_sync")));

    addButton.setGraphic(imageAdd);
    addButton.setOnAction((evt) -> createOfflinePlaylist());
    addButton.setTooltip(new Tooltip(res.getString("tooltip_add_offline")));
    renameButton.setGraphic(imageRename);
    renameButton.setOnAction(evt -> renamePlaylist());
    renameButton.setTooltip(new Tooltip(res.getString("rename_playlist")));
    deleteButton.setGraphic(imageDelete);
    deleteButton.setOnAction(evt -> deletePlaylist());
    deleteButton.setTooltip(new Tooltip(res.getString("delete_playlist")));

    loadProgressBar.setCursor(Cursor.HAND);
    volumeSlider.setCursor(Cursor.HAND);
    updatePlaylists();
    if (Settings.lastPlaylistId != null) {
      currentPlaylist =
          ((ObservableList<Playlist>) playlistsView.getItems())
              .stream()
              .filter((playlist) -> playlist.getId().equals(Settings.lastPlaylistId))
              .findFirst()
              .orElse(null);
      playlistsView.getSelectionModel().select(currentPlaylist);
      playlistsView.scrollTo(currentPlaylist);
      Platform.runLater(
          () -> {
            if (Settings.lastTrackId != null) {
              currentTrack =
                  ((ObservableList<Track>) tracksView.getItems())
                      .stream()
                      .filter((track) -> track.getId().equals(Settings.lastTrackId))
                      .findFirst()
                      .orElse(null);
              tracksView.getSelectionModel().select(currentTrack);
              tracksView.scrollTo(currentTrack);
            }
          });
    }
    new Timer()
        .scheduleAtFixedRate(
            new TimerTask() {
              @Override
              public void run() {
                updatePlayProgress();
              }
            },
            100,
            100);
    setupTracksContextMenu();

    setupShortcuts();

    Platform.runLater(
        () -> {
          tracksView.requestFocus();
        });
  }
 public void setItems() {
   items.clear();
   for (ChoiceBox<T> comboBox : comboSelected) {
     items.add(comboBox.getSelectionModel().getSelectedItem());
   }
 }
  @FXML
  void initialize() {
    map = new Simulator(canvas.getWidth(), canvas.getHeight());

    for (SimObjMaker maker : SimObjMaker.values()) {
      objectToPlace.getItems().add(maker);
    }
    objectToPlace.getSelectionModel().select(0);

    map.drawOn(canvas);
    canvas.setOnMouseClicked(
        event -> {
          SimObject obj =
              objectToPlace
                  .getSelectionModel()
                  .getSelectedItem()
                  .makeAt(event.getX(), event.getY());
          map.add(obj);
          map.drawOn(canvas);
        });

    start.setOnAction(
        event -> {
          try {
            Controller controller = ais.newInstanceOf(ai.getSelectionModel().getSelectedItem());
            if (timer != null) {
              timer.stop();
            }
            timer =
                new AnimationTimer() {
                  long next = 0;

                  @Override
                  public void handle(long now) {
                    if (now > next) {
                      next = now + INTERVAL;
                      controller.control(map);
                      map.move();
                      map.drawOn(canvas);
                      Platform.runLater(
                          () -> {
                            total.setText(Integer.toString(map.getTotalMoves()));
                            forward.setText(Integer.toString(map.getForwardMoves()));
                            collisions.setText(Integer.toString(map.getCollisions()));
                          });
                    }
                  }
                };
            timer.start();
          } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        });

    stop.setOnAction(event -> timer.stop());

    ais = new AIReflector<>(Controller.class, "robosim.ai");
    for (String typeName : ais.getTypeNames()) {
      ai.getItems().add(typeName);
    }
    if (ai.getItems().size() > 0) {
      ai.getSelectionModel().select(0);
    }

    total.setEditable(false);
    collisions.setEditable(false);
    forward.setEditable(false);
  }
  public BigDecimalFieldSample() {
    GridPane root = new GridPane();
    root.setHgap(10);
    root.setVgap(10);
    root.setPadding(new Insets(10, 10, 10, 10));
    final BigDecimalField defaultSpinner = new BigDecimalField();
    defaultSpinner.getStyleClass().add("bigDecimalField");
    final BigDecimalField decimalFormat =
        new BigDecimalField(BigDecimal.ZERO, new BigDecimal("0.05"), new DecimalFormat("#,##0.00"));
    decimalFormat.getStyleClass().add("bigDecimalField");
    final BigDecimalField percent =
        new BigDecimalField(
            BigDecimal.ZERO, new BigDecimal("0.01"), NumberFormat.getPercentInstance());
    percent.getStyleClass().add("bigDecimalField");
    final BigDecimalField localizedCurrency =
        new BigDecimalField(
            BigDecimal.ZERO, new BigDecimal("0.01"), NumberFormat.getCurrencyInstance(Locale.UK));
    localizedCurrency.getStyleClass().add("bigDecimalField");
    root.addRow(1, new Label("default"), defaultSpinner);
    root.addRow(2, new Label("custom decimal format"), decimalFormat);
    root.addRow(3, new Label("percent"), percent);
    root.addRow(4, new Label("localized currency"), localizedCurrency);
    root.addRow(
        5,
        new Label("normal TextField"),
        TextFieldBuilder.create().text("1.000,12").styleClass("bigDecimalField").build());

    final ChoiceBox styles =
        new ChoiceBox(
            FXCollections.observableArrayList(
                "rectangular corners - small font",
                "rounded corners - medium font",
                "leaf corners - large font"));
    styles
        .getSelectionModel()
        .selectedIndexProperty()
        .addListener(
            new ChangeListener<Number>() {

              @Override
              public void changed(
                  ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
                System.out.println("index" + arg2.intValue());
                Scene scene = styles.getScene();
                String pathSquared =
                    BigDecimalFieldSample.class
                        .getResource("BigDecimalField_squared.css")
                        .toExternalForm();
                String pathRounded =
                    BigDecimalFieldSample.class
                        .getResource("BigDecimalField_rounded.css")
                        .toExternalForm();
                String pathLeaf =
                    BigDecimalFieldSample.class
                        .getResource("BigDecimalField_leaf.css")
                        .toExternalForm();
                scene.getStylesheets().removeAll(pathSquared, pathRounded, pathLeaf);
                if (arg2.intValue() == 0) {
                  scene.getStylesheets().add(pathSquared);
                }
                if (arg2.intValue() == 1) {
                  scene.getStylesheets().add(pathRounded);
                }
                if (arg2.intValue() == 2) {
                  scene.getStylesheets().add(pathLeaf);
                }
              }
            });
    root.addRow(6, new Label("change css"), styles);

    Button button = new Button("Reset fields");
    button.setOnAction(
        new EventHandler<ActionEvent>() {

          @Override
          public void handle(ActionEvent arg0) {
            defaultSpinner.setNumber(new BigDecimal(Math.random() * 1000));
            decimalFormat.setNumber(new BigDecimal(Math.random() * 1000));
            percent.setNumber(new BigDecimal(Math.random()));
            localizedCurrency.setNumber(new BigDecimal(Math.random() * 1000));
            //                disabledField.setNumber(new BigDecimal(Math.random() * 1000));
          }
        });
    root.addRow(7, new Label(), button);

    getChildren().add(root);
  }