Example usage for javafx.event EventHandler EventHandler

List of usage examples for javafx.event EventHandler EventHandler

Introduction

In this page you can find the example usage for javafx.event EventHandler EventHandler.

Prototype

EventHandler

Source Link

Usage

From source file:projavafx.videoplayer3.VideoPlayer3.java

@Override
public void start(Stage primaryStage) {
    final Label message = new Label("I \u2764 Robots");
    message.setVisible(false);/*from w ww  . j  av a2  s . co m*/

    String workingDir = System.getProperty("user.dir");
    final File f = new File(workingDir, "../media/omgrobots.flv");

    final Media m = new Media(f.toURI().toString());
    m.getMarkers().put("Split", Duration.millis(3000));
    m.getMarkers().put("Join", Duration.millis(9000));

    final MediaPlayer mp = new MediaPlayer(m);

    final MediaView mv1 = new MediaView(mp);
    mv1.setViewport(new Rectangle2D(0, 0, 960 / 2, 540));
    StackPane.setAlignment(mv1, Pos.CENTER_LEFT);

    final MediaView mv2 = new MediaView(mp);
    mv2.setViewport(new Rectangle2D(960 / 2, 0, 960 / 2, 540));
    StackPane.setAlignment(mv2, Pos.CENTER_RIGHT);

    StackPane root = new StackPane();
    root.getChildren().addAll(message, mv1, mv2);
    root.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            mp.seek(Duration.ZERO);
            message.setVisible(false);
        }
    });

    final Scene scene = new Scene(root, 960, 540);
    final URL stylesheet = getClass().getResource("media.css");
    scene.getStylesheets().add(stylesheet.toString());

    primaryStage.setScene(scene);
    primaryStage.setTitle("Video Player 3");
    primaryStage.show();

    mp.setOnMarker(new EventHandler<MediaMarkerEvent>() {

        @Override
        public void handle(final MediaMarkerEvent event) {
            Platform.runLater(new Runnable() {

                @Override
                public void run() {
                    if (event.getMarker().getKey().equals("Split")) {
                        message.setVisible(true);
                        buildSplitTransition(mv1, mv2).play();
                    } else {
                        buildJoinTransition(mv1, mv2).play();
                    }
                }

            });
        }
    });
    mp.play();
}

From source file:at.ac.tuwien.qse.sepm.gui.FullscreenWindow.java

@FXML
private void initialize() {
    this.stage = new Stage();
    this.scene = new Scene(this);

    stage.setScene(scene);//from  w w  w  .  j av a 2 s  . c om

    image.setPreserveRatio(true);
    getChildren().add(0, image);

    hideButton.setOnAction((e) -> menu.setOpacity(0.0));
    menu.setOnMouseEntered(e -> menu.setOpacity(1.0));

    root.setOnKeyPressed(new EventHandler<KeyEvent>() {
        public void handle(final KeyEvent keyEvent) {
            if (keyEvent.getCode() == KeyCode.RIGHT) {
                bt_nextPressed(null);
            }
            if (keyEvent.getCode() == KeyCode.LEFT) {
                bt_previousPressed(null);
            }
            if (keyEvent.getCode() == KeyCode.ESCAPE) {
                stage.close();
            }
            if (keyEvent.getCode() == KeyCode.DIGIT1) {
                ratingPicker.setRating(Rating.BAD);
            }
            if (keyEvent.getCode() == KeyCode.DIGIT2) {
                ratingPicker.setRating(Rating.NEUTRAL);
            }
            if (keyEvent.getCode() == KeyCode.DIGIT3) {
                ratingPicker.setRating(Rating.GOOD);
            }
        }
    });

    ratingPicker.setRatingChangeHandler(this::handleRatingChange);
}

From source file:account.management.controller.expenseVoucherController.java

@Override
public void initialize(URL location, ResourceBundle resources) {

    new AutoCompleteComboBoxListener<>(this.location);
    this.location.setOnHiding((e) -> {
        Location a = this.location.getSelectionModel().getSelectedItem();
        this.location.setEditable(false);
        this.location.getSelectionModel().select(a);
    });//from   w w  w  . j  a  v  a2 s  . co  m
    this.location.setOnShowing((e) -> {
        this.location.setEditable(true);
    });

    try {
        HttpResponse<JsonNode> res = Unirest.get(MetaData.baseUrl + "get/locations").asJson();
        JSONArray array = res.getBody().getArray();
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            this.location.getItems()
                    .add(new Location(obj.getInt("id"), obj.getString("name"), obj.getString("details")));
        }
        this.amount.setOnKeyReleased((e) -> {
            calculateTotal();
        });
    } catch (Exception e) {
    }

    new Thread(() -> {
        try {
            Thread.sleep(5000);
            this.save.getScene().setOnKeyPressed(new EventHandler<KeyEvent>() {
                public void handle(final KeyEvent keyEvent) {
                    if (keyEvent.getCode() == KeyCode.ENTER) {
                        System.out.println("attempting to submit expense voucher");
                        //Stop letting it do anything else
                        keyEvent.consume();
                        onSaveButtonClick(null);
                    }
                }
            });
        } catch (InterruptedException ex) {
            Logger.getLogger(NewVoucherController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }).start();

}

From source file:guipart.AddMessageUploadFile.java

private void setScene(Stage window) {
    fileNames = new ArrayList<File>();
    fileList = new ListView<String>();
    files = FXCollections.observableArrayList();
    fileList.setItems(files);//from  w ww  . ja va  2 s.  c  o  m

    fileList.setTranslateY(-50);
    fileList.setMaxWidth(300);
    fileList.setMinHeight(150);

    Label addMessagesLabel = new Label("Add messages");
    Label loadedMessagesLabel = new Label("Loaded messages:");

    Label imageLabel2 = new Label();
    Image image2 = new Image(getClass().getResourceAsStream("/resources/gui/labelme_logo.png"));
    imageLabel2.setGraphic(new ImageView(image2));
    imageLabel2.setPrefSize(200, 200);
    HBox imageBox2 = new HBox();
    imageBox2.setAlignment(Pos.CENTER);
    imageBox2.setPadding(new Insets(20, 20, 20, 20));
    imageBox2.getChildren().add(imageLabel2);

    acceptButton = new Button("Accept All");
    browseButton = new Button("Browse");
    finishButton = new Button("Finish");
    previousButton = new Button("Previous");
    cancelButton = new Button("X");
    backButton = new Button("Back");
    pathField.setMinWidth(200);
    textCategory = new Label();

    addMessagesLabel.setFont(Font.font("Arial", FontWeight.BOLD, 28));

    HBox hBox = new HBox();
    hBox.setSpacing(20);
    hBox.getChildren().addAll(browseButton, pathField, acceptButton);
    hBox.setAlignment(Pos.CENTER);

    VBox layout = new VBox();
    layout.setSpacing(30);

    VBox filesPlaceholder = new VBox();
    filesPlaceholder.setSpacing(10);

    backButton.setTranslateY(-50);

    browseButton.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            //TODO: add more extensionFilters
            File currDir = new File(".");
            fileChooser.setInitialDirectory(currDir);
            fileChooser.getExtensionFilters().addAll((new FileChooser.ExtensionFilter("Text Files", "*.txt")));
            File file = fileChooser.showOpenDialog(window);

            if (file != null) {
                pathField.setText(file.getName());
                fileNames.add(file);
                files.add(file.getName());
            }
        }

    });

    fileList.setOnMouseClicked(e -> {
        //System.out.println(fileList.getSelectionModel().getSelectedItem());
        files.remove(fileList.getSelectionModel().getSelectedItem());
        for (File file : fileNames) {
            if (file.getName().equals(fileList.getSelectionModel().getSelectedItem())) {
                fileNames.remove(file);
                break;
            }
        }
    });

    acceptButton.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent arg0) {
            if (!fileNames.isEmpty()) {
                Categorize categorize = new Categorize();
                categorize.trainModel();

                int size = files.size();

                for (int i = 0; i < size; i++) {
                    String fileName = files.get(i);
                    for (File file : fileNames) {
                        if (file.getName().equals(fileName)) {
                            try {
                                files.add(fileName + "      "
                                        + categorize.getCategory(FileUtils.readFileToString(file, "UTF-8")));
                            } catch (IOException ex) {
                                Logger.getLogger(AddMessageUploadFile.class.getName()).log(Level.SEVERE, null,
                                        ex);
                            }
                        }
                    }

                }

                int i = 0;
                while (i < size) {
                    files.remove(0);
                    i++;
                }
                /*
                try {
                textCategory.setText("The text category is: " + categorize.getCategory(FileUtils.readFileToString(fileNames.get(fileNames.size() - 1), "UTF-8")));
                } catch (IOException ex) {
                Logger.getLogger(AddMessageUploadFile.class.getName()).log(Level.SEVERE, null, ex);
                }*/
            }
            /*
            if (pathField.getText() != null) {
            int index = pathField.getText().lastIndexOf("\\");
                    
            Label messageLabel = new Label(pathField.getText().substring(index + 1));
            messageLabel.setMinWidth(200);
            messageLabel.setMinHeight(25);
            messageLabel.setStyle("-fx-fill: orange;\n"
                    + "-fx-border-color: blue;\n"
                    + "-fx-border-width: 3;\n");
            if (filesPlaceholder.getChildren().size() != 0) {
                layout.getChildren().remove(layout.getChildren().size() - 1);
            }
                    
            filesPlaceholder.getChildren().addAll(messageLabel);
            filesPlaceholder.setAlignment(Pos.CENTER);
            filesPlaceholder.setPadding(new Insets(0, 0, 0, 50));
                    
            layout.getChildren().add(filesPlaceholder);
            }*/
        }
    });

    backButton.setOnAction(e -> {
        window.setScene(mainPage.mainPageScene);

    });

    layout.getChildren().addAll(imageLabel2, addMessagesLabel, hBox, textCategory, fileList, backButton);
    layout.setStyle("-fx-background-color: white");
    layout.setAlignment(Pos.TOP_CENTER);
    layout.setStyle("-fx-background-color: #B8EDFF;");
    scene = new Scene(layout, 900, 600);
}

From source file:org.jacp.demo.components.ContactTreeViewComponent.java

/**
 * handle menu an toolbar entries on component start up
 *//*from w  w w .j a  va  2s .  co m*/
@PostConstruct
public void PostConstructComponent(final FXComponentLayout layout) {
    final JACPToolBar north = layout.getRegisteredToolBar(ToolbarPosition.NORTH);
    final Button add = new Button("add category");
    add.getStyleClass().add("first");
    final ContactTreeViewComponent component = this;
    add.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(final ActionEvent event) {
            new ContactAddDialog(component);
        }

    });
    north.add(context.getId(), add);
}

From source file:com.sunkur.springjavafxcontroller.screen.ScreensContoller.java

private boolean swapScreen(final Parent root) {
    final Group rootGroup = getScreenRoot();
    final DoubleProperty opacity = rootGroup.opacityProperty();
    if (!isScreenEmpty()) {

        Timeline fade = new Timeline(new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)),
                new KeyFrame(new Duration(250), new EventHandler<ActionEvent>() {
                    @Override//w  ww.j  a  v  a2 s  .co  m
                    public void handle(ActionEvent t) {
                        rootGroup.getChildren().remove(0);

                        rootGroup.getChildren().add(0, root);
                        Timeline fadeIn = new Timeline(new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
                                new KeyFrame(new Duration(350), new KeyValue(opacity, 1.0)));
                        fadeIn.play();
                    }
                }, new KeyValue(opacity, 0.0)));
        fade.play();
        return true;
    } else {
        opacity.set(0.0);
        rootGroup.getChildren().add(0, root);
        Timeline fadeIn = new Timeline(new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
                new KeyFrame(new Duration(350), new KeyValue(opacity, 1.0)));
        fadeIn.play();
    }

    if (!this.stage.isShowing()) {
        this.stage.show();
    }
    return true;
}

From source file:retsys.client.controller.ClientController.java

/**
 * Initializes the controller class.//from  ww w  .  j av  a 2  s  .co m
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    //  TextFields.bindAutoCompletion(name, new Callback<AutoCompletionBinding.ISuggestionRequest, Collection<Client>>() 
    AutoCompletionBinding<Client> txt_name = TextFields.bindAutoCompletion(name,
            new Callback<AutoCompletionBinding.ISuggestionRequest, Collection<Client>>() {

                @Override
                public Collection<Client> call(AutoCompletionBinding.ISuggestionRequest param) {
                    List<Client> list = null;
                    HttpHelper helper = new HttpHelper();
                    try {
                        LovHandler lovHandler = new LovHandler("clients", "name");
                        String response = lovHandler.getSuggestions(param.getUserText());
                        list = (List<Client>) new JsonHelper().convertJsonStringToObject(response,
                                new TypeReference<List<Client>>() {
                                });
                    } catch (IOException ex) {
                        Logger.getLogger(ClientController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    return list;
                }

            }, new StringConverter<Client>() {

                @Override
                public String toString(Client object) {
                    return object.getName() + " (ID:" + object.getId() + ")";
                }

                @Override
                public Client fromString(String string) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });

    //event handler for setting other Client fields with values from selected Client object
    //fires after autocompletion
    txt_name.setOnAutoCompleted(new EventHandler<AutoCompletionBinding.AutoCompletionEvent<Client>>() {

        @Override
        public void handle(AutoCompletionBinding.AutoCompletionEvent<Client> event) {
            Client client = event.getCompletion();
            //fill other item related fields
            id.setText(splitId(name.getText()) + "");
            name.setText(splitName(name.getText()));
            phone.setText(client.getPhone());
            address.setText(client.getAddress());
            mobile.setText(client.getMobile());
            remarks.setText(client.getRemarks());
            email.setText(client.getEmail());

            populateAuditValues(client);
        }
    });
}

From source file:Main.java

@Override
public void start(Stage stage) {
    Scene scene = SceneBuilder.create().width(400).height(500).root(GroupBuilder.create().children(
            line = LineBuilder.create().startY(50).endX(200).endY(400).strokeWidth(4).stroke(Color.BLUE)
                    .build(),//from  w ww . j  a va 2s.  c om
            HBoxBuilder.create().layoutX(60).layoutY(420).spacing(10).children(startButton = ButtonBuilder
                    .create().text("Start").onAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            anim.playFromStart();
                        }
                    }).build(), pauseButton = ButtonBuilder.create().text("Pause")
                            .onAction(new EventHandler<ActionEvent>() {
                                @Override
                                public void handle(ActionEvent e) {
                                    anim.pause();
                                }
                            }).build(),
                    resumeButton = ButtonBuilder.create().text("Resume")
                            .onAction(new EventHandler<ActionEvent>() {
                                @Override
                                public void handle(ActionEvent e) {
                                    anim.play();
                                }
                            }).build(),
                    stopButton = ButtonBuilder.create().text("Stop").onAction(new EventHandler<ActionEvent>() {
                        @Override
                        public void handle(ActionEvent e) {
                            anim.stop();
                        }
                    }).build()).build())
            .build()).build();

    line.startXProperty().bind(startXVal);
    startButton.disableProperty().bind(anim.statusProperty().isNotEqualTo(Animation.Status.STOPPED));
    pauseButton.disableProperty().bind(anim.statusProperty().isNotEqualTo(Animation.Status.RUNNING));
    resumeButton.disableProperty().bind(anim.statusProperty().isNotEqualTo(Animation.Status.PAUSED));
    stopButton.disableProperty().bind(anim.statusProperty().isEqualTo(Animation.Status.STOPPED));

    stage.setScene(scene);
    stage.setTitle("Metronome 1");
    stage.show();
}

From source file:gmailclientfx.controllers.InboxController.java

public void fetchInbox() {
    ObservableList<MyMessage> data = FXCollections.observableArrayList();
    stupacId.setCellValueFactory(new PropertyValueFactory<MyMessage, Integer>("TblId"));
    stupacNaslov.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Subject"));
    stupacPosiljatelj.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("Sender"));
    stupacDatum.setCellValueFactory(new PropertyValueFactory<MyMessage, String>("DateReceived"));

    Platform.runLater(() -> {/*from  w ww.  j a  va  2 s. c om*/
        inboxTable.setItems(data);
    });
    inboxTable.setOnMousePressed(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            if (event.isPrimaryButtonDown() && event.getClickCount() == 2) {
                MyMessage selectedMsg = inboxTable.getSelectionModel().getSelectedItem();
                PregledEmailaHelper.setMsg(selectedMsg);
                try {
                    Parent root;
                    FXMLLoader loader = new FXMLLoader();
                    loader.setLocation(
                            getClass().getClassLoader().getResource("gmailclientfx/views/pregledEmaila.fxml"));
                    root = loader.load();
                    Stage stage = new Stage();
                    stage.setScene(new Scene(root));
                    stage.setTitle(PregledEmailaHelper.getMsg().getSubject() + " - "
                            + PregledEmailaHelper.getMsg().getSender());
                    stage.show();
                    PregledEmailaController pgec = loader.getController();
                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                        @Override
                        public void handle(WindowEvent event) {
                            pgec.bodyWebViewEngine.load(null);
                            System.out.println("Closing form!");
                        }

                    });
                } catch (IOException ex) {
                    Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    });

    try {
        IMAPStore store = OAuth2Authenticator.connectToImap("imap.gmail.com", 993, GmailClient.getEmail(),
                GmailClient.getAccesToken(), true);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);
        int getSeenCount = inbox.getMessageCount();
        FetchProfile fp = new FetchProfile();
        fp.add(FetchProfile.Item.ENVELOPE);
        fp.add(FetchProfileItem.FLAGS);
        fp.add(FetchProfileItem.CONTENT_INFO);
        fp.add("X-mailer");

        MimeMessage[] seenMessages = (MimeMessage[]) inbox
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), true));
        for (int i = 0; i < seenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(seenMessages[i], i + 1, "INBOX");
            data.add(msg);
        }

        MimeMessage[] unseenMessages = (MimeMessage[]) inbox
                .search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        for (int i = 0; i < unseenMessages.length; i++) {
            MyMessage msg = GmailClient.fetchMessage(unseenMessages[i], i + 1, "INBOX");
            data.add(msg);
        }

        inbox.close(false);
        store.close();
    } catch (Exception ex) {
        Logger.getLogger(InboxController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:MediaControl.java

public MediaControl(final MediaPlayer mp) {
    this.mp = mp;
    setStyle("-fx-background-color: #bfc2c7;");
    mediaView = new MediaView(mp);
    Pane mvPane = new Pane() {
    };/*  w  ww.  j  av  a2s .com*/
    mvPane.getChildren().add(mediaView);
    mvPane.setStyle("-fx-background-color: black;");
    setCenter(mvPane);
    mediaBar = new HBox();
    mediaBar.setAlignment(Pos.CENTER);
    mediaBar.setPadding(new Insets(5, 10, 5, 10));
    BorderPane.setAlignment(mediaBar, Pos.CENTER);

    final Button playButton = new Button(">");

    playButton.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            Status status = mp.getStatus();

            if (status == Status.UNKNOWN || status == Status.HALTED) {
                // don't do anything in these states
                return;
            }

            if (status == Status.PAUSED || status == Status.READY || status == Status.STOPPED) {
                // rewind the movie if we're sitting at the end
                if (atEndOfMedia) {
                    mp.seek(mp.getStartTime());
                    atEndOfMedia = false;
                }
                mp.play();
            } else {
                mp.pause();
            }
        }
    });
    mp.currentTimeProperty().addListener(new InvalidationListener() {
        public void invalidated(Observable ov) {
            updateValues();
        }
    });

    mp.setOnPlaying(new Runnable() {
        public void run() {
            if (stopRequested) {
                mp.pause();
                stopRequested = false;
            } else {
                playButton.setText("||");
            }
        }
    });

    mp.setOnPaused(new Runnable() {
        public void run() {
            System.out.println("onPaused");
            playButton.setText(">");
        }
    });

    mp.setOnReady(new Runnable() {
        public void run() {
            duration = mp.getMedia().getDuration();
            updateValues();
        }
    });

    mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
    mp.setOnEndOfMedia(new Runnable() {
        public void run() {
            if (!repeat) {
                playButton.setText(">");
                stopRequested = true;
                atEndOfMedia = true;
            }
        }
    });
    mediaBar.getChildren().add(playButton);
    // Add spacer
    Label spacer = new Label("   ");
    mediaBar.getChildren().add(spacer);

    // Add Time label
    Label timeLabel = new Label("Time: ");
    mediaBar.getChildren().add(timeLabel);

    // Add time slider
    timeSlider = new Slider();
    HBox.setHgrow(timeSlider, Priority.ALWAYS);
    timeSlider.setMinWidth(50);
    timeSlider.setMaxWidth(Double.MAX_VALUE);

    timeSlider.valueProperty().addListener(new InvalidationListener() {
        public void invalidated(Observable ov) {
            if (timeSlider.isValueChanging()) {
                // multiply duration by percentage calculated by slider position
                mp.seek(duration.multiply(timeSlider.getValue() / 100.0));
            }
        }
    });

    mediaBar.getChildren().add(timeSlider);

    // Add Play label
    playTime = new Label();
    playTime.setPrefWidth(130);
    playTime.setMinWidth(50);
    mediaBar.getChildren().add(playTime);

    // Add the volume label
    Label volumeLabel = new Label("Vol: ");
    mediaBar.getChildren().add(volumeLabel);

    // Add Volume slider
    volumeSlider = new Slider();
    volumeSlider.setPrefWidth(70);
    volumeSlider.setMaxWidth(Region.USE_PREF_SIZE);
    volumeSlider.setMinWidth(30);
    volumeSlider.valueProperty().addListener(new InvalidationListener() {
        public void invalidated(Observable ov) {
            if (volumeSlider.isValueChanging()) {
                mp.setVolume(volumeSlider.getValue() / 100.0);
            }
        }
    });
    mediaBar.getChildren().add(volumeSlider);
    setBottom(mediaBar);
}