Esempio n. 1
0
  public ToggleSwitch(boolean state) {
    Button switchBtn = new Button();
    switchBtn.setPrefWidth(40);
    switchBtn.setMaxWidth(40);
    switchedOn.set(!state);
    switchBtn.setOnAction(
        new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent t) {
            switchedOn.set(!switchedOn.get());
          }
        });
    //        switchedOn.set(state);
    setGraphic(switchBtn);

    switchedOn.addListener(
        new ChangeListener<Boolean>() {
          @Override
          public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
            if (t1) {
              setText(" ON  ");
              setStyle("-fx-background-color: green;-fx-text-fill:white;");
              setContentDisplay(ContentDisplay.RIGHT);
            } else {
              setText(" OFF ");
              setStyle("-fx-background-color: grey;-fx-text-fill:white;");
              setContentDisplay(ContentDisplay.LEFT);
            }
          }
        });

    switchedOn.set(state);
  }
Esempio n. 2
0
    public void setTask(Task<?> task) {
      if (_task != null) {
        _task.cancel();
        _animation.stop();
        visibleProperty().unbind();
        log.info("Task Canceled");
      }

      _task = task;
      if (_task != null) {
        visibleProperty().bind(task.runningProperty());
        _task
            .runningProperty()
            .addListener(
                o -> {
                  SimpleBooleanProperty running = (SimpleBooleanProperty) o;
                  if (running.get()) {
                    _animation.play();
                  } else {
                    _animation.stop();
                  }
                });

        task.setOnFailed(
            e -> {
              log.error(_task.getMessage());
              setTask(null);
            });
      }
    }
  public DrawerLayout() {
    AnchorPane.setTopAnchor(toggleLayer, 0d);
    AnchorPane.setRightAnchor(toggleLayer, 0d);
    AnchorPane.setBottomAnchor(toggleLayer, 0d);
    AnchorPane.setLeftAnchor(toggleLayer, 0d);
    toggleLayer.setBackground(
        new Background(new BackgroundFill(Color.BLACK, new CornerRadii(0d), new Insets(0))));
    toggleLayer.setOpacity(0);
    toggleLayer.setVisible(false);

    toggleLayer.setOnMouseClicked(
        evt -> {
          if (evt.getButton().equals(MouseButton.PRIMARY)) {
            if (drawerOpened) {
              closeDrawer();
            }
          }
        });

    tableScreen.bind(widthProperty().lessThan(responsiveWidth).or(responsiveWidth.isEqualTo(0)));
    tableScreen.addListener(
        (observable, oldValue, newValue) -> {
          responsiveBehavior(newValue);
        });
  }
Esempio n. 4
0
  private static SimpleBooleanProperty createBooleanProperty(
      final String name, final boolean defaultValue) {
    final SimpleBooleanProperty property =
        new SimpleBooleanProperty(null, name, p.getBoolean(name, defaultValue));
    property.addListener(booleanChangeListener);

    return property;
  }
Esempio n. 5
0
  /**
   * Creates a binding that is true when the active view is the view with "css-id" <code>ID</code>
   */
  private BooleanBinding activeViewBinding(ContentView view) {
    SimpleBooleanProperty isActiveView = new SimpleBooleanProperty(false);
    viewDisplay
        .getCurrentView()
        .addListener(
            (obs, oldValue, newValue) ->
                isActiveView.set(viewDisplay.getCurrentView().get().equals(view)));
    BooleanBinding binding = Bindings.createBooleanBinding(() -> isActiveView.get(), isActiveView);

    return binding;
  }
 public void setInvalid(String reasonWhyInvalid) {
   if (reasonWhyInvalid == null || reasonWhyInvalid.length() == 0) {
     throw new RuntimeException(
         "Supply a reason when setting the SimpleValidBooleanBinding to false");
   }
   super.set(false);
   reasonWhyInvalid_.set(reasonWhyInvalid);
 }
 public void openDrawer() {
   if (tableScreen.getValue()) {
     drawerOpened = true;
     drawerAnimation();
     if (drawerListener != null) {
       drawerListener.onDrawerOpened(nav);
     }
   }
 }
 public void closeDrawer() {
   if (tableScreen.getValue()) {
     drawerOpened = false;
     drawerAnimation();
     if (drawerListener != null) {
       drawerListener.onDrawerClosed(nav);
     }
   }
 }
 /** @see javafx.beans.property.BooleanPropertyBase#fireValueChangedEvent() */
 @Override
 protected void fireValueChangedEvent() {
   try {
     super.fireValueChangedEvent();
   } catch (Exception e) {
     log_.error(
         "Severe API messup - exception within one of the bindings attached to this binding!", e);
   }
 }
Esempio n. 10
0
  private void startNewGame() {
    playable.set(true);
    message.setText("");

    deck.refill();

    dealer.reset();
    player.reset();

    dealer.takeCard(deck.drawCard());
    dealer.takeCard(deck.drawCard());
    player.takeCard(deck.drawCard());
    player.takeCard(deck.drawCard());
  }
Esempio n. 11
0
  private void handleAlert(WebEvent<String> event) {
    numberOfAlerts.setValue(Integer.toString(Integer.valueOf(numberOfAlerts.getValue()) + 1));
    String message = event.getData();

    /*
     * Handle all the external onAlert event handlers first.
     */
    for (EventHandler<WebEvent<String>> handler : alertListeners) handler.handle(event);

    /*
     * Finally display an alert box if the operator demands it.
     */
    if (showAlerts.getValue()) {
      dialog.title("JavaScript Alert").message(message).showInformation();
      resetParents();
    }
  }
Esempio n. 12
0
  private void endGame() {
    playable.set(false);

    int dealerValue = dealer.valueProperty().get();
    int playerValue = player.valueProperty().get();
    String winner = "Exceptional case: d: " + dealerValue + " p: " + playerValue;

    // the order of checking is important
    if (dealerValue == 21
        || playerValue > 21
        || dealerValue == playerValue
        || (dealerValue < 21 && dealerValue > playerValue)) {
      winner = "DEALER";
    } else if (playerValue == 21 || dealerValue > 21 || playerValue > dealerValue) {
      winner = "PLAYER";
    }

    message.setText(winner + " WON");
  }
Esempio n. 13
0
 static {
   isProxyingEnabled.addListener(
       (observable, oldValue, newValue) -> {
         if (newValue) {
           System.setProperty("http.proxySet", "true");
           System.setProperty("http.proxyHost", "127.0.0.1");
           System.setProperty("http.proxyPort", "8080");
           System.setProperty("https.proxySet", "true");
           System.setProperty("https.proxyHost", "127.0.0.1");
           System.setProperty("https.proxyPort", "8080");
         } else {
           System.clearProperty("http.proxySet");
           System.clearProperty("http.proxyHost");
           System.clearProperty("http.proxyPort");
           System.clearProperty("https.proxySet");
           System.clearProperty("https.proxyHost");
           System.clearProperty("https.proxyPort");
         }
       });
 }
Esempio n. 14
0
  /** Constructor */
  public MyUpdater(Label stat, Stage st, VBox sl, ProgressBar bar) {
    status = stat;
    progressBar = bar;
    splashLayout = sl;
    splashStage = st;

    Yes = new Button("yes");
    Yes.setOnAction(event1 -> downloadupdate());
    Yes.setMaxWidth(Double.MAX_VALUE);
    No = new Button("No");
    No.setOnAction(
        event -> {
          splashStage.hide();
          isready.set(true);
        });
    No.setMaxWidth(Double.MAX_VALUE);

    updateLayout = new HBox(Yes, No);
    HBox.setHgrow(Yes, Priority.ALWAYS);
    HBox.setHgrow(No, Priority.ALWAYS);
  }
Esempio n. 15
0
 public void resetGame() {
   try {
     timer.cancel();
   } catch (IllegalStateException e) {
   }
   timer = new Timer();
   timer.scheduleAtFixedRate(new FoodThrowingTask(), 0, 600);
   timer.scheduleAtFixedRate(new HealthPotionFallingTask(), 5000, 10000);
   foodList = new ArrayList<Food>();
   potionsList = new ArrayList<Potion>();
   usersCombinedScore = 0;
   fallingStuffSpeed = 90;
   currentLevel = startingLevel;
   healthRemaining = healthAtStart;
   setHealthoMeter();
   user1.setPosition(200, 365);
   user2.setPosition(600, 365);
   user1.setVelocity(0, 0);
   user2.setVelocity(0, 0);
   animationTimer.start();
   gameOver.set(false);
   System.out.println("Game has been reset");
 }
Esempio n. 16
0
 private void beautifyOrRepairHTML(String mode) {
   logger.info("beautifying html");
   try {
     CodeEditor editor = currentEditor.getValue();
     EditorPosition currentCursorPosition = editor.getEditorCursorPosition();
     String code = editor.getCode();
     if (currentEditorIsXHTML.get()) {
       try {
         Resource resource = currentXHTMLResource.get();
         resource.setData(code.getBytes("UTF-8"));
         switch (mode) {
           case "format":
             code = formatAsXHTML(code);
             break;
           case "repair":
             code = repairXHTML(code);
             break;
         }
         resource.setData(code.getBytes("UTF-8"));
       } catch (UnsupportedEncodingException e) {
         // never happens
       }
     }
     editor.setCode(code);
     editor.setEditorCursorPosition(currentCursorPosition);
     editor.scrollTo(currentCursorPosition);
     book.setBookIsChanged(true);
   } catch (IOException | JDOMException e) {
     logger.error("", e);
     Dialogs.create()
         .owner(tabPane)
         .title("Formatierung nicht möglich")
         .message(
             "Kann Datei nicht formatieren. Bitte die Fehlermeldung an den Hersteller weitergeben.")
         .showException(e);
   }
 }
Esempio n. 17
0
 public boolean getCanUndo() {
   return canUndo.get();
 }
Esempio n. 18
0
  public void init() {
    currentEditor.addListener(
        (observable, oldValue, newValue) -> {
          canUndo.unbind();
          canRedo.unbind();
          if (newValue != null) {
            currentEditorIsXHTML.setValue(
                currentEditor.getValue().getMediaType().equals(MediaType.XHTML));
            canUndo.bind(currentEditor.getValue().canUndoProperty());
            canRedo.bind(currentEditor.getValue().canRedoProperty());
          } else {
            currentEditorIsXHTML.setValue(false);
            canUndo.setValue(false);
            canRedo.setValue(false);
          }
        });

    MenuItem separatorItem = new SeparatorMenuItem();
    // Html menu
    contextMenuXHTML = new ContextMenu();
    contextMenuXHTML.setAutoFix(true);
    contextMenuXHTML.setAutoHide(true);

    Menu clipsItem = new Menu("Clips");
    clipManager
        .getClipsRoot()
        .addEventHandler(
            TreeItem.<Clip>childrenModificationEvent(),
            event -> {
              clipsItem.getItems().clear();
              writeClipMenuItemChildren(clipManager.getClipsRoot(), clipsItem);
            });
    contextMenuXHTML.getItems().add(clipsItem);
    contextMenuXHTML.getItems().add(separatorItem);

    MenuItem itemRepairHTML = new MenuItem("HTML reparieren");
    itemRepairHTML.setOnAction(
        e -> {
          beautifyOrRepairHTML("repair");
        });
    contextMenuXHTML.getItems().add(itemRepairHTML);

    MenuItem itemBeautifyHTML = new MenuItem("HTML formatieren");
    itemBeautifyHTML.setOnAction(
        e -> {
          beautifyOrRepairHTML("format");
        });
    contextMenuXHTML.getItems().add(itemBeautifyHTML);

    contextMenuXHTML.getItems().add(separatorItem);

    MenuItem openInExternalBrowserItem = new MenuItem("In externem Browser öffnen");
    openInExternalBrowserItem.setOnAction(
        e -> {
          openInExternalBrowser(currentEditor);
        });
    contextMenuXHTML.getItems().add(openInExternalBrowserItem);

    // XML menu
    contextMenuXML = new ContextMenu();
    contextMenuXML.setAutoFix(true);
    contextMenuXML.setAutoHide(true);

    MenuItem generateUuidMenuItem = new MenuItem("Neue UUID generieren");
    generateUuidMenuItem.setOnAction(
        e -> {
          book.getMetadata().generateNewUuid();
          bookBrowserManager.refreshOpf();
        });
    contextMenuXML.getItems().add(generateUuidMenuItem);
    currentXMLResource.addListener(
        new ChangeListener<Resource>() {
          @Override
          public void changed(
              ObservableValue<? extends Resource> observable,
              Resource oldValue,
              Resource newValue) {
            if (newValue != null
                && currentXMLResource.get().mediaTypeProperty().getValue().equals(MediaType.OPF)) {
              generateUuidMenuItem.visibleProperty().setValue(true);
            } else {
              generateUuidMenuItem.visibleProperty().setValue(false);
            }
          }
        });

    MenuItem separatorItem2 = new SeparatorMenuItem();
    contextMenuXML.getItems().add(separatorItem2);
    separatorItem2.visibleProperty().bind(generateUuidMenuItem.visibleProperty());

    MenuItem itemRepairXML = new MenuItem("XML reparieren");
    itemRepairXML.setOnAction(
        e -> {
          beautifyOrRepairXML("repair");
        });
    contextMenuXML.getItems().add(itemRepairXML);

    MenuItem itemBeautifyXML = new MenuItem("XML formatieren");
    itemBeautifyXML.setOnAction(
        e -> {
          beautifyOrRepairXML("format");
        });
    contextMenuXML.getItems().add(itemBeautifyXML);

    // css menu
    contextMenuCSS = new ContextMenu();
    contextMenuCSS.setAutoFix(true);
    contextMenuCSS.setAutoHide(true);
    MenuItem formatCSSOneLineItem = new MenuItem("Styles in je einer Zeile formatieren");
    formatCSSOneLineItem.setOnAction(e -> beautifyCSS("one_line"));
    contextMenuCSS.getItems().add(formatCSSOneLineItem);

    MenuItem formatCSSMultipleLinesItem = new MenuItem("Styles in mehreren Zeilen formatieren");
    formatCSSMultipleLinesItem.setOnAction(e -> beautifyCSS("multiple_lines"));
    contextMenuCSS.getItems().add(formatCSSMultipleLinesItem);
  }
Esempio n. 19
0
  /** Función encargada de descargar la actualización */
  private void downloadupdate() {
    // El usuario aceptó la actualización entonces se le pide seleccione un directirio para guardar
    final File file = new DirectoryChooser().showDialog(splashStage);

    // Creamos el archivo para escribir.
    final File filetowrite = new File(file.getAbsolutePath() + "/" + FILE_NAME);

    // Eliminamos los botones de control.
    splashLayout.getChildren().remove(updateLayout);

    // Animamos la barra de progreso.
    progressBar.setProgress(ProgressBar.INDETERMINATE_PROGRESS);

    // Tarea encargada de realizar la descarga.
    Task download =
        new Task() {
          @Override
          protected Object call() throws Exception {
            updateMessage(". . . D O W N L O A D I N G . . ");

            // Creamos el objeto que contendrá el enlace.
            URL source = new URL(checkupdates.get());
            if (source != null) {
              // Copiamos el arhcivo del enlace.
              Files.copy(
                  source.openStream(), filetowrite.toPath(), StandardCopyOption.REPLACE_EXISTING);
              updateMessage(" READY ");
              Thread.sleep(SHORT_WAIT_MILLIS);
            } else {
              cancel();
            }
            return null;
          }
        };

    // Permitimos que la tarea maneje el texto del splash
    status.textProperty().bind(download.messageProperty());

    // Si se ha terminado la descarga.
    download.setOnSucceeded(
        event -> {

          // Tarea encargada de mostrar que se a terminado la descarga.
          Task timer =
              new Task() {
                @Override
                protected Object call() throws Exception {
                  updateMessage("PLEASE START THE NEW VERSION");
                  Thread.sleep(SHORT_WAIT_MILLIS);
                  return null;
                }
              };

          // Permitimos que la tarea maneje el texto del splash
          status.textProperty().bind(timer.messageProperty());

          // cuando termine la tarea cerramos la aplicación.
          timer.setOnSucceeded(event1 -> System.exit(0));

          // Mostramos animación de la barra de progreso.
          showFinishProgress(timer);
        });

    // Si ha fallado la descarga.
    download.setOnFailed(
        event -> {

          // Tarea encargada de mostrar que ha fallado la descarga.
          Task timer =
              new Task() {
                @Override
                protected Object call() throws Exception {
                  updateMessage("Descarga Fallida");
                  Thread.sleep(SHORT_WAIT_MILLIS);
                  return null;
                }
              };

          // Permitimos que la tarea maneje el texto del splash
          status.textProperty().bind(timer.messageProperty());

          timer.setOnSucceeded(
              event1 -> {
                splashStage.close();
                isready.set(true);
              });
          // Mostramos animación de la barra de progreso.
          showFinishProgress(timer);
        });

    // Creamos el hilo y lo iniciamos.
    new Thread(download).start();
  }
 public void setValid() {
   super.set(true);
   reasonWhyInvalid_.set("");
 }
Esempio n. 21
0
 public boolean getIsRNA() {
   return isRNA.get();
 }
Esempio n. 22
0
  private Parent createContent() throws IOException {
    dealer = new Hand(dealerCards.getChildren());
    player = new Hand(playerCards.getChildren());

    Pane root = new Pane();
    root.setPrefSize(windowWidth, windowHeight);

    Region background = new Region();
    background.setPrefSize(windowWidth, windowHeight);
    background.setStyle("-fx-background-image: url('res/images/casino.jpg')");

    HBox rootLayout = new HBox(5);
    rootLayout.setPadding(new Insets(5, 5, 5, 5));
    //        Rectangle leftBG = new Rectangle(550, 560);
    //        leftBG.setArcWidth(50);
    //        leftBG.setArcHeight(50);
    //        leftBG.setFill(Color.GREEN);
    //
    Canvas canvas = new Canvas(560, 560);

    BufferedImage imgi;
    GraphicsContext gcfx = canvas.getGraphicsContext2D();
    // Graphics gc = canvas.getGraphics();
    Image zbyszek = new Image("/res/images/table.png", 560, 560, true, false);

    gcfx.setFill(DARKSLATEGRAY);
    gcfx.fillRoundRect(0, 0, 550, 300, 10, 100);
    gcfx.setFill(BLACK);
    gcfx.drawImage(zbyszek, 0, 280);

    //        try {
    //            imgi = ImageIO.read(Card.class.getResource("/res/images/table.png"));
    //
    //            gcfx.drawImage(imgi, 300, 300, null);
    //            canvas.setVisible(true);
    //        } catch (Exception e) {
    //        }

    Rectangle rightBG = new Rectangle(230, 560);
    rightBG.setArcWidth(50);
    rightBG.setArcHeight(50);
    rightBG.setFill(Color.ORANGE);

    // LEFT
    VBox leftVBox = new VBox(50);
    leftVBox.setAlignment(Pos.TOP_CENTER);

    Text dealerScore = new Text("Dealer: ");
    Text playerScore = new Text("Player: ");

    leftVBox.getChildren().addAll(dealerScore, dealerCards, message, playerCards, playerScore);

    // RIGHT
    VBox rightVBox = new VBox(20);
    rightVBox.setAlignment(Pos.CENTER);

    // final TextField bet = new TextField("BET");
    // bet.setDisable(true);
    // bet.setMaxWidth(50);
    // Text money = new Text("MONEY");
    Button btnPlay = new Button("PLAY");
    Button btnHit = new Button("HIT");
    Button btnStand = new Button("STAND");

    HBox buttonsHBox = new HBox(15, btnHit, btnStand);
    buttonsHBox.setAlignment(Pos.CENTER);

    // rightVBox.getChildren().addAll(bet, btnPlay, money, buttonsHBox);
    rightVBox.getChildren().addAll(btnPlay, buttonsHBox);

    // ADD BOTH STACKS TO ROOT LAYOUT
    rootLayout
        .getChildren()
        .addAll(new StackPane(canvas, leftVBox), new StackPane(rightBG, rightVBox));
    root.getChildren().addAll(background, rootLayout);

    // BIND PROPERTIES
    btnPlay.disableProperty().bind(playable);
    btnHit.disableProperty().bind(playable.not());
    btnStand.disableProperty().bind(playable.not());

    playerScore
        .textProperty()
        .bind(new SimpleStringProperty("Player: ").concat(player.valueProperty().asString()));
    dealerScore
        .textProperty()
        .bind(new SimpleStringProperty("Dealer: ").concat(dealer.valueProperty().asString()));

    player
        .valueProperty()
        .addListener(
            (obs, old, newValue) -> {
              if (newValue.intValue() >= 21) {
                endGame();
              }
            });

    dealer
        .valueProperty()
        .addListener(
            (obs, old, newValue) -> {
              if (newValue.intValue() >= 21) {
                endGame();
              }
            });

    // INIT BUTTONS
    btnPlay.setOnAction(
        event -> {
          startNewGame();
        });

    btnHit.setOnAction(
        event -> {
          player.takeCard(deck.drawCard());
        });

    btnStand.setOnAction(
        event -> {
          while (dealer.valueProperty().get() < 17) {
            dealer.takeCard(deck.drawCard());
          }

          endGame();
        });

    return root;
  }
Esempio n. 23
0
  /** Función encargada de revisar si existen actualizaciones. */
  private void checkforupdates() {
    /**
     * Esta Función descarga un archivo txt que contiene la información y enlace de descarga de las
     * distintas versiones de la aplicación, compara la versión del programa y si encuentra una
     * versión mas reciente en el archivo manda llamar a la función de descarga.
     */

    // Tarea encargada de revisar si hay actualización.
    checkupdates =
        new Task<String>() {
          @Override
          protected String call() throws Exception {

            // Avisamos al usuario que se van a revisar las actualziaciones.
            updateMessage("CHECKING FOR UPDATES");
            Thread.sleep(500);

            // Creamos una dirección para el archivo de texto.
            URL updatefile = new URL(UPDATE_TXT);

            // Si existe el archivo de texto.
            if (updatefile != null) {
              // Creamos un lector.
              BufferedReader in =
                  new BufferedReader(new InputStreamReader(updatefile.openStream()));

              // Buffer.
              String str;
              // Para cada linea.
              while ((str = in.readLine()) != null) {
                // Partimos cada linea "repositorio; version; URL" notese que el separador es "; "
                String[] buf = str.split("; ");

                // Si la versión es mayor y el repositorio corresponde entonces preguntamos si se
                // desea descargar.
                if ((Double.parseDouble(buf[1]) > VERSION)
                    && (buf[0].equalsIgnoreCase(REPOSITORY))) {
                  updateMessage(
                      " A NEW VERSION OF TRUDISP IS AVAILABLE\n V_: " + buf[1] + "\n DOWNLOAD?");
                  isupdating = true;
                  return buf[2];
                } else {
                  isupdating = false;
                }
              }
            } else // No se ha podido establecer conexión con el archivo de texto.
            {
              updateMessage("CONNECTION ERROR");
              Thread.sleep(SHORT_WAIT_MILLIS);
              isupdating = false;
              cancel();
            }
            return null;
          }
        };

    // Permitimos que la tarea maneje los mensajes de la barra de estado.
    status.textProperty().bind(checkupdates.messageProperty());

    // Si se ha terminado la tarea
    checkupdates.setOnSucceeded(
        event -> {
          if (isupdating) {
            // Agregamos los botones de control.
            splashLayout.getChildren().add(updateLayout);
            splashStage.sizeToScene();
            progressBar.setProgress(0);
          } else {
            // Cerramos el splash y avisamos que se ha terminado.
            splashStage.close();
            isready.set(true);
          }
        });

    // Si ha fallado latarea.
    checkupdates.setOnFailed(
        event -> {
          splashStage.close();
          isready.set(true);
        });

    // Creamos e iniciamos el hilo.
    new Thread(checkupdates).start();
  }