Example usage for javafx.scene.image ImageView ImageView

List of usage examples for javafx.scene.image ImageView ImageView

Introduction

In this page you can find the example usage for javafx.scene.image ImageView ImageView.

Prototype

public ImageView(Image image) 

Source Link

Document

Allocates a new ImageView object using the given image.

Usage

From source file:Main.java

@Override
public void start(Stage stage) {
    stage.setTitle("Menu Sample");
    Scene scene = new Scene(new VBox(), 400, 350);
    scene.setFill(Color.OLDLACE);

    name.setFont(new Font("Verdana Bold", 22));
    binName.setFont(new Font("Arial Italic", 10));
    pic.setFitHeight(150);/*  w  ww .jav  a2 s  .  c o m*/
    pic.setPreserveRatio(true);
    description.setWrapText(true);
    description.setTextAlignment(TextAlignment.JUSTIFY);

    shuffle();

    MenuBar menuBar = new MenuBar();

    // --- Graphical elements
    final VBox vbox = new VBox();
    vbox.setAlignment(Pos.CENTER);
    vbox.setSpacing(10);
    vbox.setPadding(new Insets(0, 10, 0, 10));
    vbox.getChildren().addAll(name, binName, pic, description);

    // --- Menu File
    Menu menuFile = new Menu("File");
    MenuItem add = new MenuItem("Shuffle", new ImageView(new Image("src/menusample/new.png")));
    add.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            shuffle();
            vbox.setVisible(true);
        }
    });

    MenuItem clear = new MenuItem("Clear");
    clear.setAccelerator(KeyCombination.keyCombination("Ctrl+X"));
    clear.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            vbox.setVisible(false);
        }
    });

    MenuItem exit = new MenuItem("Exit");
    exit.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            System.exit(0);
        }
    });

    menuFile.getItems().addAll(add, clear, new SeparatorMenuItem(), exit);

    // --- Menu Edit
    Menu menuEdit = new Menu("Edit");
    Menu menuEffect = new Menu("Picture Effect");

    final ToggleGroup groupEffect = new ToggleGroup();
    for (Entry effect : effects) {
        RadioMenuItem itemEffect = new RadioMenuItem((String) effect.getKey());
        itemEffect.setUserData(effect.getValue());
        itemEffect.setToggleGroup(groupEffect);
        menuEffect.getItems().add(itemEffect);
    }

    final MenuItem noEffects = new MenuItem("No Effects");
    noEffects.setDisable(true);
    noEffects.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent t) {
            pic.setEffect(null);
            groupEffect.getSelectedToggle().setSelected(false);
            noEffects.setDisable(true);
        }
    });

    groupEffect.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
        public void changed(ObservableValue ov, Toggle old_toggle, Toggle new_toggle) {
            if (groupEffect.getSelectedToggle() != null) {
                Effect effect = (Effect) groupEffect.getSelectedToggle().getUserData();
                pic.setEffect(effect);
                noEffects.setDisable(false);
            } else {
                noEffects.setDisable(true);
            }
        }
    });

    menuEdit.getItems().addAll(menuEffect, noEffects);

    // --- Menu View
    Menu menuView = new Menu("View");
    CheckMenuItem titleView = createMenuItem("Title", name);
    CheckMenuItem binNameView = createMenuItem("Binomial name", binName);
    CheckMenuItem picView = createMenuItem("Picture", pic);
    CheckMenuItem descriptionView = createMenuItem("Decsription", description);

    menuView.getItems().addAll(titleView, binNameView, picView, descriptionView);
    menuBar.getMenus().addAll(menuFile, menuEdit, menuView);

    // --- Context Menu
    final ContextMenu cm = new ContextMenu();
    MenuItem cmItem1 = new MenuItem("Copy Image");
    cmItem1.setOnAction(new EventHandler<ActionEvent>() {
        public void handle(ActionEvent e) {
            Clipboard clipboard = Clipboard.getSystemClipboard();
            ClipboardContent content = new ClipboardContent();
            content.putImage(pic.getImage());
            clipboard.setContent(content);
        }
    });

    cm.getItems().add(cmItem1);
    pic.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent e) {
            if (e.getButton() == MouseButton.SECONDARY)
                cm.show(pic, e.getScreenX(), e.getScreenY());
        }
    });

    ((VBox) scene.getRoot()).getChildren().addAll(menuBar, vbox);

    stage.setScene(scene);
    stage.show();
}

From source file:net.rptools.tokentool.util.ImageUtil.java

public static Image scaleImage(Image source, double targetWidth, double targetHeight, boolean preserveRatio) {
    ImageView imageView = new ImageView(source);
    imageView.setPreserveRatio(preserveRatio);
    imageView.setFitWidth(targetWidth);/*from   ww  w.  j a va 2  s. c om*/
    imageView.setFitHeight(targetHeight);
    return imageView.snapshot(null, null);
}

From source file:com.mycompany.pfinanzaspersonales.BuscadorController.java

@FXML
private void btnBuscar(ActionEvent event) throws IOException {

    String desde_t = "", hasta_t = "";

    if (input_desde.getValue() != null) {
        desde_t = input_desde.getValue().toString();
    }/*  ww  w.ja va 2s  . com*/

    if (input_hasta.getValue() != null) {
        hasta_t = input_hasta.getValue().toString();
    }

    final String desde = desde_t;
    final String hasta = hasta_t;

    final Task<Void> tarea = new Task<Void>() {
        @Override
        protected Void call() throws Exception {

            HttpResponse response;
            List<NameValuePair> parametros = new ArrayList<NameValuePair>();

            parametros.add(new BasicNameValuePair("tipo", cbb_tipo.getValue().toString()));
            parametros.add(new BasicNameValuePair("pago", cbb_pago.getValue().toString()));
            parametros.add(new BasicNameValuePair("desde", desde));
            parametros.add(new BasicNameValuePair("hasta", hasta));

            System.out.println(desde);
            response = JSON.request(Config.URL + "usuarios/buscar.json", parametros);

            JSONObject jObject = JSON.JSON(response);
            tabla_json = new ArrayList<TablaBuscar>();

            try {

                editar.setCellValueFactory(new PropertyValueFactory<TablaBuscar, String>("editar"));
                eliminar.setCellValueFactory(new PropertyValueFactory<TablaBuscar, String>("eliminar"));
                fecha.setCellValueFactory(new PropertyValueFactory<TablaBuscar, String>("fecha"));
                categoria.setCellValueFactory(new PropertyValueFactory<TablaBuscar, String>("categoria"));
                tpago.setCellValueFactory(new PropertyValueFactory<TablaBuscar, String>("pago"));
                tmonto.setCellValueFactory(new PropertyValueFactory<TablaBuscar, String>("monto"));
                ttipo.setCellValueFactory(new PropertyValueFactory<TablaBuscar, String>("tipo"));

                tabla_json = new ArrayList<TablaBuscar>();

                if (!jObject.get("data").equals(null)) {
                    JSONArray jsonArr = jObject.getJSONArray("data");
                    for (int i = 0; i < jsonArr.length(); i++) {
                        JSONObject data_json = jsonArr.getJSONObject(i);
                        tabla_json.add(new TablaBuscar(data_json.get("idgastos").toString(),
                                data_json.get("idgastos").toString(), data_json.get("idgastos").toString(),
                                data_json.get("monto").toString(), data_json.get("fecha").toString(),
                                data_json.get("nom_mediopago").toString(),
                                data_json.get("categoria").toString(), data_json.get("tipo").toString()));
                    }
                }
                tabla_buscador.setItems(FXCollections.observableArrayList(tabla_json));

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void succeeded() {
            super.succeeded();

            eliminar.setCellFactory(new Callback<TableColumn<String, String>, TableCell<String, String>>() {
                @Override
                public TableCell<String, String> call(TableColumn<String, String> p) {

                    return new TableCell<String, String>() {
                        @Override
                        public void updateItem(String item, boolean empty) {

                            super.updateItem(item, empty);

                            if (!isEmpty() && !empty) {

                                final VBox vbox = new VBox(5);
                                Image image = new Image(getClass().getResourceAsStream("/Imagenes/delete.png"));
                                final Button boton = new Button("", new ImageView(image));
                                boton.setOnAction(new EventHandler<ActionEvent>() {
                                    @Override
                                    public void handle(ActionEvent event) {

                                        Action response = Dialogs.create().title("Eliminar Gasto")
                                                .message("Ests seguro que desaeas eliminar el gasto?")
                                                .showConfirm();

                                        if (response == Dialog.ACTION_YES) {

                                            TablaBuscar tabla = tabla_json.get(getTableRow().getIndex());

                                            List<NameValuePair> parametros = new ArrayList<NameValuePair>();

                                            String url = "";
                                            if (tabla.getTipo() == "Gastos") {
                                                parametros
                                                        .add(new BasicNameValuePair("idgastos", tabla.getId()));
                                                url = Config.URL + "gastos/eliminar.json";
                                            } else {
                                                parametros.add(
                                                        new BasicNameValuePair("idingresos", tabla.getId()));
                                                url = Config.URL + "ingresos/eliminar.json";
                                            }

                                            HttpResponse responseJSON = JSON.request(url, parametros);
                                            JSONObject jObject = JSON.JSON(responseJSON);
                                            int code = Integer.parseInt(jObject.get("code").toString());

                                            if (code == 201) {
                                                int selectdIndex = getTableRow().getIndex();
                                                tabla_json.remove(selectdIndex);
                                                tabla_buscador.getItems().remove(selectdIndex);
                                            } else {
                                                Dialogs.create().title("Error sincronizacin").message(
                                                        "Hubo un error al intentar eliminar . ERROR: 301")
                                                        .showInformation();
                                            }

                                        }

                                    }
                                });

                                vbox.getChildren().add(boton);
                                setGraphic(vbox);
                            } else {
                                setGraphic(null);
                            }
                        }
                    };
                }
            });

            editar.setCellFactory(new Callback<TableColumn<String, String>, TableCell<String, String>>() {
                @Override
                public TableCell<String, String> call(TableColumn<String, String> p) {

                    return new TableCell<String, String>() {
                        @Override
                        public void updateItem(String item, boolean empty) {

                            super.updateItem(item, empty);

                            if (!isEmpty() && !empty) {

                                final VBox vbox = new VBox(5);
                                Image image = new Image(getClass().getResourceAsStream("/Imagenes/edit.png"));
                                final Button boton = new Button("", new ImageView(image));
                                boton.setOnAction(new EventHandler<ActionEvent>() {
                                    @Override
                                    public void handle(ActionEvent event) {

                                        TablaBuscar tabla = tabla_json.get(getTableRow().getIndex());

                                        Parent parent = null;
                                        if (tabla.getTipo() == "Gastos") {
                                            AgregarGastos AG = AgregarGastos.getInstance();

                                            AG.setID(tabla.getId());
                                            AG.setMonto(tabla.getMonto());
                                            AG.setCategoria(tabla.getCategoria());
                                            AG.setPago(tabla.getPago());
                                            AG.setActualizacion(true);

                                            try {
                                                parent = FXMLLoader.load(this.getClass()
                                                        .getResource("/fxml/AgregarGastos.fxml"));
                                            } catch (IOException ex) {
                                                Logger.getLogger(FXMLController.class.getName())
                                                        .log(Level.SEVERE, null, ex);
                                            }
                                        } else {
                                            AgregarIngresos AI = AgregarIngresos.getInstance();

                                            AI.setID(tabla.getId());
                                            AI.setMonto(tabla.getMonto());
                                            AI.setCategoria(tabla.getCategoria());
                                            AI.setPago(tabla.getPago());
                                            AI.setActualizar(true);

                                            try {
                                                parent = FXMLLoader.load(this.getClass()
                                                        .getResource("/fxml/AgregarIngresos.fxml"));
                                            } catch (IOException ex) {
                                                Logger.getLogger(FXMLController.class.getName())
                                                        .log(Level.SEVERE, null, ex);
                                            }
                                        }

                                        Stage stage = new Stage();
                                        Scene scene = new Scene(parent);
                                        stage.setScene(scene);
                                        stage.show();

                                    }
                                });

                                vbox.getChildren().add(boton);
                                setGraphic(vbox);
                            } else {
                                setGraphic(null);
                            }
                        }
                    };
                }
            });

        }
    };
    new Thread(tarea).start();
}

From source file:account.management.controller.inventory.InsertStockController.java

@FXML
private void onSaveButtonClick(ActionEvent event) {
    this.save.setDisable(true);
    try {// w  w  w.  j  a v a 2s.  c om
        String date = new SimpleDateFormat("yyyy-MM-dd")
                .format(new SimpleDateFormat("yyyy-MM-dd").parse(this.date.getValue().toString()));
        JSONArray array = new JSONArray();
        for (int i = 0; i < this.conatiner.getChildren().size(); i++) {
            HBox row = (HBox) this.conatiner.getChildren().get(i);
            ComboBox<Product> item = (ComboBox) row.getChildren().get(0);
            TextField qty = (TextField) row.getChildren().get(1);
            TextField rate = (TextField) row.getChildren().get(2);

            JSONObject obj = new JSONObject();
            obj.put("id", item.getSelectionModel().getSelectedItem().getId());
            obj.put("quantity", qty.getText());
            obj.put("rate", rate.getText());

            array.put(obj);

        }

        Unirest.post(MetaData.baseUrl + "products/ledger")
                .field("voucher_type", this.voucher_type.getSelectionModel().getSelectedItem())
                .field("date", date).field("products", array).asString();
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText(null);
        alert.setContentText("Ledger has been saved successfully!");
        alert.setGraphic(new ImageView(new Image("resources/success.jpg")));
        alert.showAndWait();
        this.save.setDisable(false);
    } catch (Exception ex) {
        Logger.getLogger(InsertStockController.class.getName()).log(Level.SEVERE, null, ex);
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText(null);
        alert.setContentText("Sorry!! there is an error. Please try again.");
        alert.setGraphic(new ImageView(new Image("resources/error.jpg")));
        alert.showAndWait();
    }
}

From source file:Main.java

private GridPane addGridPane() {

    GridPane grid = new GridPane();
    grid.setHgap(10);/*from ww  w .j  av  a 2s . c om*/
    grid.setVgap(10);
    grid.setPadding(new Insets(0, 10, 0, 10));

    // Category in column 2, row 1
    Text category = new Text("Sales:");
    category.setFont(Font.font("Arial", FontWeight.BOLD, 20));
    grid.add(category, 1, 0);

    // Title in column 3, row 1
    Text chartTitle = new Text("Current Year");
    chartTitle.setFont(Font.font("Arial", FontWeight.BOLD, 20));
    grid.add(chartTitle, 2, 0);

    // Subtitle in columns 2-3, row 2
    Text chartSubtitle = new Text("Goods and Services");
    grid.add(chartSubtitle, 1, 1, 2, 1);

    // House icon in column 1, rows 1-2
    ImageView imageHouse = new ImageView(new Image(Main.class.getResourceAsStream("graphics/house.png")));
    grid.add(imageHouse, 0, 0, 1, 2);

    // Left label in column 1 (bottom), row 3
    Text goodsPercent = new Text("Goods\n80%");
    GridPane.setValignment(goodsPercent, VPos.BOTTOM);
    grid.add(goodsPercent, 0, 2);

    // Chart in columns 2-3, row 3
    ImageView imageChart = new ImageView(new Image(Main.class.getResourceAsStream("graphics/piechart.png")));
    grid.add(imageChart, 1, 2, 2, 1);

    // Right label in column 4 (top), row 3
    Text servicesPercent = new Text("Services\n20%");
    GridPane.setValignment(servicesPercent, VPos.TOP);
    grid.add(servicesPercent, 3, 2);

    //        grid.setGridLinesVisible(true);
    return grid;
}

From source file:slideshow.client.ui.ClientUIController.java

/**
 * ListView item clicked//from   w  ww  .  j  a v  a 2s  .  c o  m
 * @param event 
 */
@FXML
void listClicked(MouseEvent event) {

    //Accepts Double Clicks
    if (event.getClickCount() == this.LIST_VIEW_CLICKS) {
        System.out.println("slideshow.client.ui.ClientUIController.listClicked.doubleClick");

        //Gets Selected Item
        String selected = this.songListView.getSelectionModel().getSelectedItem().toString();

        URI uri = this.mSongsLocal.get(selected);

        if (uri != null) {
            this.mMusic.pause();
            this.mMusic = new Music(uri);

            this.playSongButton.setGraphic(new ImageView(new Image("/slideshow/client/ui/icons/pause.png")));

            this.mMusic.play();
        }
    }
}

From source file:photobooth.views.ExplorerPane.java

private void addXButton() throws IOException {
    Button button = new Button();
    button.setGraphic(// w  w  w .  ja  v a2 s. com
            new ImageView(new Image(getClass().getResource("/photobooth/images/exit.png").openStream())));
    button.setStyle("-fx-background-color: transparent;");
    button.setLayoutX(730);
    button.setLayoutY(10);
    button.setMaxSize(50, 50);
    button.setMinSize(50, 50);
    button.getStyleClass().add("blueButton");
    this.getChildren().add(button);
    button.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            Global.getInstance().setSceneRoot(HomePane.getInstance());
        }
    });
}

From source file:dpfmanager.shell.interfaces.gui.component.dessign.DessignView.java

private void addTreeView() {
    // Root node (my computer)
    CheckBoxTreeItem<String> rootNode = new CheckBoxTreeItem<>(getHostName(),
            new ImageView(new Image("images/computer.png")));
    checkTreeView = new CheckTreeView<>(rootNode);
    rootNode.addEventHandler(TreeItem.<Object>branchExpandedEvent(), new ExpandEventHandler(checkTreeView));
    rootNode.addEventHandler(TreeItem.<Object>branchCollapsedEvent(), new CollapseEventHandler());

    // Root items
    Iterable<Path> rootDirectories = FileSystems.getDefault().getRootDirectories();
    for (Path name : rootDirectories) {
        if (Files.isDirectory(name)) {
            FilePathTreeItem treeNode = new FilePathTreeItem(name);
            rootNode.getChildren().add(treeNode);
        }//from www. ja  va2s  .  co m
    }
    rootNode.setExpanded(true);

    // Add data and add to gui
    treeViewHBox.getChildren().clear();
    treeViewHBox.getChildren().add(checkTreeView);
    HBox.setHgrow(checkTreeView, Priority.ALWAYS);
}

From source file:net.rptools.tokentool.util.ImageUtil.java

private static Image autoCropImage(Image imageSource) {
    ImageView croppedImageView = new ImageView(imageSource);
    PixelReader pixelReader = imageSource.getPixelReader();

    int imageWidth = (int) imageSource.getWidth();
    int imageHeight = (int) imageSource.getHeight();
    int minX = imageWidth, minY = imageHeight, maxX = 0, maxY = 0;

    // Find the first and last pixels that are not transparent to create a bounding viewport
    for (int readY = 0; readY < imageHeight; readY++) {
        for (int readX = 0; readX < imageWidth; readX++) {
            Color pixelColor = pixelReader.getColor(readX, readY);

            if (!pixelColor.equals(Color.TRANSPARENT)) {
                if (readX < minX)
                    minX = readX;//from w w w.  j a va 2 s  .  c o m
                if (readX > maxX)
                    maxX = readX;

                if (readY < minY)
                    minY = readY;
                if (readY > maxY)
                    maxY = readY;
            }
        }
    }

    if (maxX - minX <= 0 || maxY - minY <= 0)
        return new WritableImage(1, 1);

    // Create a viewport to clip the image using snapshot
    Rectangle2D viewPort = new Rectangle2D(minX, minY, maxX - minX, maxY - minY);
    SnapshotParameters parameter = new SnapshotParameters();
    parameter.setViewport(viewPort);
    parameter.setFill(Color.TRANSPARENT);

    return croppedImageView.snapshot(parameter, null);
}

From source file:Main.java

private FlowPane addFlowPane() {

    FlowPane flow = new FlowPane();
    flow.setPadding(new Insets(5, 0, 5, 0));
    flow.setVgap(4);//from  w  w  w  .  j  a  v a2s .co  m
    flow.setHgap(4);
    flow.setPrefWrapLength(170); // preferred width allows for two columns
    flow.setStyle("-fx-background-color: DAE6F3;");

    ImageView pages[] = new ImageView[8];
    for (int i = 0; i < 8; i++) {
        pages[i] = new ImageView(
                new Image(Main.class.getResourceAsStream("graphics/chart_" + (i + 1) + ".png")));
        flow.getChildren().add(pages[i]);
    }

    return flow;
}