Example usage for javafx.scene.control Button setOnAction

List of usage examples for javafx.scene.control Button setOnAction

Introduction

In this page you can find the example usage for javafx.scene.control Button setOnAction.

Prototype

public final void setOnAction(EventHandler<ActionEvent> value) 

Source Link

Usage

From source file:TwoButtons.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    final RowLayout layout = new RowLayout();
    shell.setLayout(layout);/*from w  w w .jav  a2 s .com*/

    /* Create the SWT button */
    final org.eclipse.swt.widgets.Button swtButton =
            new org.eclipse.swt.widgets.Button(shell, SWT.PUSH);
    swtButton.setText("SWT Button");

    /* Create an FXCanvas */
    final FXCanvas fxCanvas = new FXCanvas(shell, SWT.NONE) {

        public Point computeSize(int wHint, int hHint, boolean changed) {
            getScene().getWindow().sizeToScene();
            int width = (int) getScene().getWidth();
            int height = (int) getScene().getHeight();
            return new Point(width, height);
        }
    };
    /* Create a JavaFX Group node */
    Group group = new Group();
    /* Create a JavaFX button */
    final Button jfxButton = new Button("JFX Button");
    /* Assign the CSS ID ipad-dark-grey */
    jfxButton.setId("ipad-dark-grey");
    /* Add the button as a child of the Group node */
    group.getChildren().add(jfxButton);
    /* Create the Scene instance and set the group node as root */
    Scene scene = new Scene(group, Color.rgb(shell.getBackground().getRed(), shell.getBackground().getGreen(),
            shell.getBackground().getBlue()));
    /* Attach an external stylesheet */
    scene.getStylesheets().add("twobuttons/Buttons.css");
    fxCanvas.setScene(scene);

    /* Add Listeners */
    swtButton.addListener(SWT.Selection, new Listener() {

        public void handleEvent(Event event) {
            jfxButton.setText("JFX Button: Hello from SWT");
            shell.layout();
        }
    });
    jfxButton.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent event) {
            swtButton.setText("SWT Button: Hello from JFX");
            shell.layout();
        }
    });

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

From source file:de.pixida.logtest.designer.commons.SelectFileButton.java

public static Button createButtonWithFileSelection(final TextField inputFieldShowingPath, final String icon,
        final String title, final String fileMask, final String fileMaskDescription) {
    final Button selectLogFileButton = new Button("Select");
    selectLogFileButton.setGraphic(Icons.getIconGraphics(icon));
    selectLogFileButton.setOnAction(event -> {
        final FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle(title);/*from   ww  w.j  av  a 2 s  .  c om*/
        if (StringUtils.isNotBlank(fileMask) && StringUtils.isNotBlank(fileMaskDescription)) {
            fileChooser.getExtensionFilters()
                    .add(new FileChooser.ExtensionFilter(fileMaskDescription, fileMask));
        }
        File initialDirectory = new File(inputFieldShowingPath.getText().trim());
        if (!initialDirectory.isDirectory()) {
            initialDirectory = initialDirectory.getParentFile();
        }
        if (initialDirectory == null || !initialDirectory.isDirectory()) {
            if (lastFolder != null) {
                initialDirectory = lastFolder;
            } else {
                initialDirectory = new File(".");
            }
        }
        fileChooser.setInitialDirectory(initialDirectory);
        final File selectedFile = fileChooser.showOpenDialog(((Node) event.getTarget()).getScene().getWindow());
        if (selectedFile != null) {
            inputFieldShowingPath.setText(selectedFile.getAbsolutePath());
            final File parent = selectedFile.getParentFile();
            if (parent != null && parent.isDirectory()) {
                lastFolder = parent;
            }
        }
    });
    return selectLogFileButton;
}

From source file:Main.java

private static Node createConfirmationPanel() {
    final Label acceptanceLabel = new Label("Not Available");

    final Button acceptButton = new Button("Accept");
    acceptButton.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(final ActionEvent event) {
            acceptanceLabel.setText("Accepted");
        }//w  ww  . j  a va 2  s  .  c  o m
    });

    final Button declineButton = new Button("Decline");
    declineButton.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(final ActionEvent event) {
            acceptanceLabel.setText("Declined");
        }
    });

    final HBox panel = createHBox(6, acceptButton, declineButton, acceptanceLabel);
    panel.setAlignment(Pos.CENTER_LEFT);
    configureBorder(panel);

    return panel;
}

From source file:nl.mvdr.umvc3replayanalyser.gui.ErrorMessagePopup.java

/**
 * Handles an exception that caused program startup to fail, by showing an error message to the user.
 * /*  w w w.j  av  a 2s .  c o m*/
 * @param title
 *            title for the dialog
 * @param errorMessage
 *            error message
 * @param stage
 *            stage in which to show the error message
 * @param exception
 *            exception that caused the error
 */
public static void show(String title, String errorMessage, final Stage stage, Exception exception) {
    log.info("Showing error message dialog to indicate that startup failed.");

    // Create the error dialog programatically without relying on FXML, to minimize the chances of further failure.

    stage.setTitle(title);

    // Error message text.
    Text text = new Text(errorMessage);

    // Text area containing the stack trace. Not visible by default.
    String stackTrace;
    if (exception != null) {
        stackTrace = ExceptionUtils.getStackTrace(exception);
    } else {
        stackTrace = "No more details available.";
    }
    final TextArea stackTraceArea = new TextArea(stackTrace);
    stackTraceArea.setEditable(false);
    stackTraceArea.setVisible(false);

    // Details button for displaying the stack trace.
    Button detailsButton = new Button();
    detailsButton.setText("Details");
    detailsButton.setOnAction(new EventHandler<ActionEvent>() {
        /** {@inheritDoc} */
        @Override
        public void handle(ActionEvent event) {
            log.info("User clicked Details.");
            stackTraceArea.setVisible(!stackTraceArea.isVisible());
        }
    });

    // OK button for closing the dialog.
    Button okButton = new Button();
    okButton.setText("OK");
    okButton.setOnAction(new EventHandler<ActionEvent>() {
        /** {@inheritDoc} */
        @Override
        public void handle(ActionEvent event) {
            log.info("User clicked OK, closing the dialog.");
            stage.close();
        }
    });

    // Horizontal box containing the buttons, to make sure they are always centered.
    HBox buttonsBox = new HBox(5);
    buttonsBox.getChildren().add(detailsButton);
    buttonsBox.getChildren().add(okButton);
    buttonsBox.setAlignment(Pos.CENTER);

    // Layout constraints.
    AnchorPane.setTopAnchor(text, Double.valueOf(5));
    AnchorPane.setLeftAnchor(text, Double.valueOf(5));
    AnchorPane.setRightAnchor(text, Double.valueOf(5));

    AnchorPane.setTopAnchor(stackTraceArea, Double.valueOf(31));
    AnchorPane.setLeftAnchor(stackTraceArea, Double.valueOf(5));
    AnchorPane.setRightAnchor(stackTraceArea, Double.valueOf(5));
    AnchorPane.setBottomAnchor(stackTraceArea, Double.valueOf(36));

    AnchorPane.setLeftAnchor(buttonsBox, Double.valueOf(5));
    AnchorPane.setRightAnchor(buttonsBox, Double.valueOf(5));
    AnchorPane.setBottomAnchor(buttonsBox, Double.valueOf(5));

    AnchorPane root = new AnchorPane();
    root.getChildren().addAll(text, stackTraceArea, buttonsBox);

    stage.setScene(new Scene(root));

    // Use a standard program icon if possible.
    try {
        stage.getIcons().add(Icons.get().getRandomPortrait());
    } catch (IllegalStateException e) {
        log.warn("Failed to load icon for error dialog; proceeding with default JavaFX icon.", e);
    }

    stage.show();

    // Default size should also be the minimum size.
    stage.setMinWidth(stage.getWidth());
    stage.setMinHeight(stage.getHeight());

    log.info("Error dialog displayed.");
}

From source file:cz.lbenda.gui.controls.TextAreaFrmController.java

/** Create button which can open text editor */
public static Button createOpenButton(String windowTitle, @Nonnull Supplier<String> oldValueSupplier,
        @Nonnull Consumer<String> newValueConsumer) {
    String title = windowTitle == null ? msgDefaultWindowTitle : windowTitle;
    Button result = new Button(null, new ImageView(BUTTON_IMAGE));
    result.setTooltip(new Tooltip(msgBtnOpenInEditor_tooltip));
    BorderPane.setAlignment(result, Pos.TOP_RIGHT);
    result.setOnAction(event -> {
        Tuple2<Parent, TextAreaFrmController> tuple2 = TextAreaFrmController.createNewInstance();
        tuple2.get2().textProperty().setValue(oldValueSupplier.get());
        tuple2.get2().textProperty()//from   w w w .j  a v  a 2  s . c o  m
                .addListener((observable, oldValue, newValue) -> newValueConsumer.accept(newValue));
        Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        DialogHelper.getInstance().openWindowInCenterOfStage(stage, tuple2.get2().getMainPane(), title);
    });
    return result;
}

From source file:main.TestManager.java

/**
 * Displays given test. Intended for testing and
 * evaluating correct answers. (student mode only)
 * @param test test to display//from  www.j a v a  2s  .c o m
 * @param stage 
 */
public static void displayTest(Test test, Stage stage) {
    Debugger.println(test.getName() + " - is displayed.");
    TabPane tabPane = new TabPane();
    int counter = 1;
    for (Question q : test.getQuestions()) {
        Label instruction = new Label(q.question);
        instruction.setStyle("-fx-font-size: 20");
        Pane choices = q.getPaneOfChoices();
        VBox vbox = new VBox(instruction, choices);
        vbox.setSpacing(10);
        Tab tab = new Tab("Otzka " + Integer.toString(counter), vbox);
        tab.setStyle("-fx-font-size: 20");
        tabPane.getTabs().add(tab);
        counter++;
    }

    Button finish = new Button("Ukon?i test!");
    finish.setStyle("-fx-font-size: 20");
    finish.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            try {
                test.evaluate(stage);
            } catch (IOException e) {
                Alert alert = new Alert(AlertType.ERROR);
                alert.setContentText("Ojoj, vyskytol sa problm. Aplikcia sa mus ukon?i.");
                alert.showAndWait();
                System.exit(0);
            }
        }
    });
    Button nextQuestion = new Button("alia");
    nextQuestion.setStyle("-fx-font-size: 20");
    nextQuestion.setOnAction(e -> tabPane.getSelectionModel().selectNext());
    HBox buttons = new HBox(finish, nextQuestion);
    buttons.setSpacing(10);
    buttons.setAlignment(Pos.BOTTOM_CENTER);
    VBox outerVBox = new VBox(tabPane, buttons);
    outerVBox.setPadding(new Insets(10, 10, 10, 10));
    Scene scene = new Scene(outerVBox);
    stage.setScene(scene);
    stage.show();
}

From source file:Main.java

@Override
public void start(Stage stage) {
    String yahooURL = "http://www.java2s.com";
    Button openURLButton = new Button("Go!");
    openURLButton.setOnAction(e -> getHostServices().showDocument(yahooURL));

    Scene scene = new Scene(openURLButton);
    stage.setScene(scene);/*  ww  w.  ja  v  a  2  s .c  o m*/
    stage.setTitle("Knowing the Host");
    stage.show();
}

From source file:Main.java

@Override
public void start(Stage stage) {
    Button exitBtn = new Button("Exit");
    exitBtn.setOnAction(e -> Platform.exit());

    VBox root = new VBox();
    root.getChildren().add(exitBtn);//from   ww  w.java  2 s . com

    Scene scene = new Scene(root, 300, 50);
    stage.setScene(scene);
    stage.setTitle("Hello JavaFX Application with a Scene");
    stage.show();
}

From source file:Main.java

@Override
 public void start(Stage stage) {
     String name = Thread.currentThread().getName();
     System.out.println("start() method: " + name);

     // Add an Exit button to the scene
     Button exitBtn = new Button("Exit");
     exitBtn.setOnAction(e -> Platform.exit());

     Scene scene = new Scene(new Group(exitBtn), 300, 100);
     stage.setScene(scene);/*from   w  ww. j a  v  a2 s .  c o  m*/
     stage.setTitle("JavaFX Application Life Cycle");
     stage.show();
 }

From source file:Main.java

@Override
public void start(Stage stage) {

    Button openURLButton = new Button("Go!");
    openURLButton.setOnAction(e -> {
        HostServices host = this.getHostServices();

        System.out.println("CodeBase:" + host.getCodeBase());

        System.out.println("DocumentBase:" + host.getDocumentBase());

        System.out.println("Environment:" + host.getWebContext());

        System.out.println("Splash Image URI" + host.resolveURI(host.getDocumentBase(), "splash.jpg"));
    });/*from w w w.  j  av a 2 s . c  om*/

    Scene scene = new Scene(openURLButton);
    stage.setScene(scene);
    stage.setTitle("Knowing the Host");
    stage.show();
}