Example usage for javafx.embed.swing SwingFXUtils toFXImage

List of usage examples for javafx.embed.swing SwingFXUtils toFXImage

Introduction

In this page you can find the example usage for javafx.embed.swing SwingFXUtils toFXImage.

Prototype

public static WritableImage toFXImage(BufferedImage bimg, WritableImage wimg) 

Source Link

Document

Snapshots the specified BufferedImage and stores a copy of its pixels into a JavaFX Image object, creating a new object if needed.

Usage

From source file:snpviewer.SnpViewer.java

public void convertSampleViewToImage(final SnpFile s, final Pane pane, final String chrom, final String path) {
    WritableImage image;/*from w  w w  .ja v a2 s . c o m*/
    try {
        image = pane.snapshot(null, null);
    } catch (IllegalStateException ex) {
        Dialogs.showErrorDialog(null, "Error while attempting to convert" + " view to image file",
                "PNG conversion failed", "SNP Viewer", ex);
        return;
    }

    final DrawPaneToPng drawToPng = new DrawPaneToPng(image);
    drawToPng.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent t) {
            File pngFile;
            if (path != null && path.length() > 0) {
                pngFile = new File(s.getOutputDirectoryName() + "/" + path + "/" + chrom + ".png");
            } else {
                pngFile = new File(s.getOutputDirectoryName() + "/" + chrom + ".png");
            }
            try {
                if (!pngFile.getParentFile().exists()) {
                    boolean madeDir = pngFile.getParentFile().mkdir();
                    if (madeDir == false) {
                        Dialogs.showErrorDialog(null, "Unable to make sub directory"
                                + " when converting dynamic view to image file. Please " + "check permissions.",
                                "PNG conversion failed", "SNP Viewer");
                        return;
                    }
                }
                Files.copy(drawToPng.getImageFile().toPath(), pngFile.toPath(), REPLACE_EXISTING);
                BufferedImage bufferedImage = ImageIO.read(pngFile);
                Image image = SwingFXUtils.toFXImage(bufferedImage, null);

                ImageView chromImage = new ImageView(image);
                // chromImage.setCache(true);
                for (Iterator it = pane.getChildren().iterator(); it.hasNext();) {
                    Object line = it.next();
                    if (line instanceof Line) {
                        /*Line l = (Line) line;
                        l.startXProperty().unbind();
                        l.endXProperty().unbind();
                        l.endYProperty().unbind();*/
                    } else if (line instanceof ImageView) {
                        ImageView l = (ImageView) line;
                        l.fitHeightProperty().unbind();
                        l.fitWidthProperty().unbind();
                    }
                }
                pane.getChildren().clear();
                pane.getChildren().add(chromImage);

                chromImage.fitWidthProperty().bind(pane.widthProperty());
                chromImage.fitHeightProperty().bind(pane.heightProperty());
            } catch (IOException ex) {
                Dialogs.showErrorDialog(null,
                        "IOException while attempting to convert" + " dynamic view to image file",
                        "PNG conversion failed", "SNP Viewer", ex);
            }
        }
    });
    drawToPng.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent t) {
            Dialogs.showErrorDialog(null, "Error attempting to convert" + " dynamic view to image file",
                    "PNG conversion failed", "SNP Viewer");

        }
    });
    drawToPng.start();
}

From source file:sopho.Ofeloumenoi.AddOfeloumenoiController.java

@Override
public void initialize(URL url, ResourceBundle rb) {

    tekna.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

        @Override/*from ww w. ja  v a  2 s  .  c o  m*/
        public void handle(MouseEvent event) {
            if (prefs.getPrefs("tableTipOfeloumenoi").equals("true")) {
                sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                        "?",
                        "  ?       '?  '  ?  . ? ?    enter   ?  .         .",
                        "notify");
                cm.showAndWait();
                prefs.setPrefs("tableTipOfeloumenoi", "false");
            }
        }
    });

    anenergos.selectedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (newValue) {
                barcode.setStyle("-fx-background-color: #cc334a; -fx-text-fill:white;");
                if (showAnenergosTip.equals("true")) {
                    sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                            "?...",
                            "  ?   ?,    barcode      ?    ?   ? ?  ?? ?.        !",
                            "confirm");
                    cm.showAndWait();
                    prefs.setPrefs("showAnenergosTip", "false");
                }
            } else {
                barcode.setStyle("");
            }
        }
    });

    anergos.selectedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            epaggelma.setDisable(!newValue);//if the anergos checkbox is selected the epaggelma textFiels is disabled and vise versa
        }
    });

    //we use a listener to know if the user adds a photo using the TakePhoto class
    PhotoListener.strProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue o, Object oldVal, Object newVal) {
            if (PhotoListener.getStr() != null) {
                changePhotoButton.setText(" ?");
            }
            PhotoID = (String) newVal;

            BufferedImage bf = bfImage(PhotoID);

            if (bf != null) {
                Image im = SwingFXUtils.toFXImage(bf, null);
                image.setImage(im);
            }

        }
    });

    //initialzing tekna table
    data = getInitialTableData();

    tekna.setItems(data);
    tekna.setEditable(true);
    etosCol.setCellValueFactory(new PropertyValueFactory<tableManager, String>("etos"));

    //lets make the table cells editable
    etosCol.setCellFactory(TextFieldTableCell.forTableColumn());
    etosCol.setOnEditCommit(new EventHandler<CellEditEvent<tableManager, String>>() {

        @Override
        public void handle(CellEditEvent<tableManager, String> t) {
            if (!NumberUtils.isNumber(t.getNewValue())) {
                sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                        "?!",
                        "      ?  ?  ??. ?    ?  .",
                        "error");
                cm.showAndWait();
                ((tableManager) t.getTableView().getItems().get(t.getTablePosition().getRow()))
                        .setEtos("?  ");
            } else {
                ((tableManager) t.getTableView().getItems().get(t.getTablePosition().getRow()))
                        .setEtos(t.getNewValue());
            }
        }
    });

    tekna.getColumns().setAll(etosCol);
    //end of initialization of tekna table

    //initialize oikKatastasi combobox
    oikKatastasi.getItems().addAll("", "", "", "?");

    //initialize asfForeas comboBox
    asfForeas.getItems().addAll("", "", "", "", "",
            "", "", "", "  ", "");
}

From source file:sopho.Ofeloumenoi.EditOfeloumenoiController.java

@Override
public void initialize(URL url, ResourceBundle rb) {

    tekna.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

        @Override/* w  w  w.j av a2 s. com*/
        public void handle(MouseEvent event) {
            if (prefs.getPrefs("tableTipOfeloumenoi").equals("true")) {
                sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                        "?",
                        "  ?       '?  '  ?  . ? ?    enter   ?  .         .",
                        "notify");
                cm.showAndWait();
                prefs.setPrefs("tableTipOfeloumenoi", "false");
            }
        }
    });

    //initialize oikKatastasi combobox
    oikKatastasi.getItems().addAll("", "", "", "?");

    //initialize asfForeas comboBox
    asfForeas.getItems().addAll("", "", "", "", "",
            "", "", "", "  ", "");

    try {

        rs.first();//move the cursor to the first row
        if (selectedIndex > 0) {//only if we need to move from the first line
            rs.relative(selectedIndex);//move to the row that we selected at the previous scene
        }

        //keep the selected ofeloumenos id
        selID = rs.getInt("id");

        System.out.println("The selected rs row is " + rs.getRow());

        oldBarcode = rs.getString("barcode");

        //now we will set all the fields using the data from database
        barcode.setText(rs.getString("barcode"));
        eponimo.setText(rs.getString("eponimo"));
        onoma.setText(rs.getString("onoma"));
        patronimo.setText(rs.getString("patronimo"));
        mitronimo.setText(rs.getString("mitronimo"));

        if (rs.getDate("imGennisis") != null) {
            imGennisis.setValue(rs.getDate("imGennisis").toLocalDate());
        }

        dieuthinsi.setText(rs.getString("dieuthinsi"));
        dimos.setText(rs.getString("dimos"));
        tilefono.setText(rs.getString("tilefono"));
        anergos.setSelected((rs.getInt("anergos") != 0)); //if 0 set false, else set true
        epaggelma.setText(rs.getString("epaggelma"));
        eisodima.setText(rs.getString("eisodima"));
        eksartiseis.setText(rs.getString("eksartiseis"));

        PhotoID = rs.getString("PhotoID");
        if (PhotoID != null) {
            //we have a picture stored at the database.
            BufferedImage bf = bfImage(PhotoID);

            if (bf != null) {
                Image im = SwingFXUtils.toFXImage(bf, null);
                image.setImage(im);
            }

            //and we set the button bellow image to " ?"
            changePhotoButton.setText(" ?");
        }

        afm.setText(rs.getString("afm"));
        tautotita.setText(rs.getString("tautotita"));
        ethnikotita.setText(rs.getString("ethnikotita"));
        metanastis.setSelected(rs.getInt("metanastis") != 0);
        roma.setSelected(rs.getInt("roma") != 0);
        int oikKatIndex = rs.getInt("oikKatastasi");
        if (oikKatIndex >= 0) {
            oikKatastasi.getSelectionModel().select(oikKatIndex);
        }

        //we add data to tekna table using the tableManager class bellow

        politeknos.setSelected(rs.getInt("politeknos") != 0);
        monogoneiki.setSelected(rs.getInt("monogoneiki") != 0);
        mellousaMama.setSelected(rs.getInt("mellousaMama") != 0);
        amea.setSelected(rs.getInt("amea") != 0);
        int asfForeasIndex = rs.getInt("asfForeas");
        if (asfForeasIndex >= 0) {
            asfForeas.getSelectionModel().select(asfForeasIndex);
        }
        xronios.setSelected(rs.getInt("xronios") != 0);
        pathisi.setText(rs.getString("pathisi"));
        anoTon60.setSelected(rs.getInt("anoTon60") != 0);
        monaxiko.setSelected(rs.getInt("monaxikos") != 0);
        emfiliVia.setSelected(rs.getInt("emfiliVia") != 0);
        spoudastis.setSelected(rs.getInt("spoudastis") != 0);
        int anenergosFlag = rs.getInt("anenergos");
        if (anenergosFlag == 1) {
            barcode.setStyle("-fx-background-color: #cc334a; -fx-text-fill:white;");
        }
        anenergos.setSelected(anenergosFlag != 0);
        loipa.setText(rs.getString("loipa"));

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

    //adding a listener to anenergos checkbox to know if the user checks it
    anenergos.selectedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (newValue) {
                barcode.setStyle("-fx-background-color: #cc334a; -fx-text-fill:white;");
                if (showAnenergosTip.equals("true")) {
                    sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                            "?...",
                            "  ?   ?,    barcode      ?    ?   ? ?  ?? ?.        !",
                            "confirm");
                    cm.showAndWait();
                    prefs.setPrefs("showAnenergosTip", "false");
                }
            } else {
                barcode.setStyle("");
            }
        }
    });

    //we use a listener to know if the user adds a photo using the TakePhoto class
    PhotoListener.strProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue o, Object oldVal, Object newVal) {
            PhotoID = (String) newVal;
            BufferedImage bf = bfImage(PhotoID);

            if (bf != null) {
                Image im = SwingFXUtils.toFXImage(bf, null);
                image.setImage(im);
            }
        }
    });

    //initialzing tekna table
    data = getInitialTableData();

    tekna.setItems(data);
    tekna.setEditable(true);
    etosCol.setCellValueFactory(new PropertyValueFactory<tableManager, String>("etos"));

    //lets make the table cells editable
    etosCol.setCellFactory(TextFieldTableCell.forTableColumn());
    etosCol.setOnEditCommit(new EventHandler<CellEditEvent<tableManager, String>>() {

        @Override
        public void handle(CellEditEvent<tableManager, String> t) {
            if (!NumberUtils.isNumber(t.getNewValue())) {
                sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null,
                        "?!",
                        "      ?  ?  ??. ?    ?  .",
                        "error");
                cm.showAndWait();
                ((tableManager) t.getTableView().getItems().get(t.getTablePosition().getRow()))
                        .setEtos("?  ");
            } else {
                ((tableManager) t.getTableView().getItems().get(t.getTablePosition().getRow()))
                        .setEtos(t.getNewValue());
            }
        }
    });

    tekna.getColumns().setAll(etosCol);
    //end of initialization of tekna table

}

From source file:tachyon.view.ProjectProperties.java

public ProjectProperties(JavaProject project, Window w) {
    this.project = project;
    stage = new Stage();
    stage.initOwner(w);/*from w  w w  .  j  av  a2s  .c om*/
    stage.initModality(Modality.APPLICATION_MODAL);
    stage.setWidth(600);
    stage.setTitle("Project Properties - " + project.getProjectName());
    stage.getIcons().add(tachyon.Tachyon.icon);
    stage.setResizable(false);
    HBox mai, libs, one, two, thr, fou;
    ListView<String> compileList, runtimeList;
    Button compileAdd, compileRemove, preview, selectIm, runtimeAdd, runtimeRemove;
    TextField iconField;
    stage.setScene(new Scene(new VBox(5, pane = new TabPane(
            new Tab("Library Settings",
                    box1 = new VBox(15,
                            libs = new HBox(10, new Label("External Libraries"), libsView = new ListView<>(),
                                    new VBox(5, addJar = new Button("Add Jar"),
                                            removeJar = new Button("Remove Jar"))))),
            new Tab("Program Settings",
                    new ScrollPane(box2 = new VBox(15, one = new HBox(10, new Label("Main-Class"),
                            mainClass = new TextField(project.getMainClassName()),
                            select = new Button("Select")),
                            two = new HBox(10, new Label("Compile-Time Arguments"),
                                    compileList = new ListView<>(),
                                    new VBox(5, compileAdd = new Button("Add Argument"),
                                            compileRemove = new Button("Remove Argument")))))),
            new Tab("Deployment Settings",
                    box3 = new VBox(15, thr = new HBox(10, new Label("Icon File"),
                            iconField = new TextField(project.getFileIconPath()),
                            preview = new Button("Preview Image"), selectIm = new Button("Select Icon")),
                            fou = new HBox(10, new Label("Runtime Arguments"), runtimeList = new ListView<>(),
                                    new VBox(5, runtimeAdd = new Button("Add Argument"),
                                            runtimeRemove = new Button("Remove Argument")))))),
            new VBox(15, mai = new HBox(10, cancel = new Button("Cancel"), confirm = new Button("Confirm"))))));
    if (applyCss.get()) {
        stage.getScene().getStylesheets().add(css);
    }
    for (Tab b : pane.getTabs()) {
        b.setClosable(false);
    }
    mainClass.setPromptText("Main-Class");
    box1.setPadding(new Insets(5, 10, 5, 10));
    mai.setAlignment(Pos.CENTER_RIGHT);
    mai.setPadding(box1.getPadding());
    libs.setAlignment(Pos.CENTER);
    one.setAlignment(Pos.CENTER);
    two.setAlignment(Pos.CENTER);
    thr.setAlignment(Pos.CENTER);
    fou.setAlignment(Pos.CENTER);
    box1.setAlignment(Pos.CENTER);
    box2.setPadding(box1.getPadding());
    box2.setAlignment(Pos.CENTER);
    box3.setPadding(box1.getPadding());
    box3.setAlignment(Pos.CENTER);
    mainClass.setEditable(false);
    mainClass.setPrefWidth(200);
    for (JavaLibrary lib : project.getAllLibs()) {
        libsView.getItems().add(lib.getBinaryAbsolutePath());
    }
    for (String sa : project.getCompileTimeArguments().keySet()) {
        compileList.getItems().add(sa + ":" + project.getCompileTimeArguments().get(sa));
    }
    for (String sa : project.getRuntimeArguments()) {
        runtimeList.getItems().add(sa);
    }
    compileAdd.setOnAction((e) -> {
        Dialog<Pair<String, String>> dialog = new Dialog<>();
        dialog.setTitle("Compiler Argument");
        dialog.initOwner(stage);
        dialog.setHeaderText("Entry the argument");

        ButtonType loginButtonType = new ButtonType("Done", ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField username = new TextField();
        username.setPromptText("Key");
        TextField password = new TextField();
        password.setPromptText("Value");

        grid.add(new Label("Key:"), 0, 0);
        grid.add(username, 1, 0);
        grid.add(new Label("Value:"), 0, 1);
        grid.add(password, 1, 1);

        Node loginButton = dialog.getDialogPane().lookupButton(loginButtonType);
        loginButton.setDisable(true);

        username.textProperty().addListener((observable, oldValue, newValue) -> {
            loginButton.setDisable(newValue.trim().isEmpty());
        });

        dialog.getDialogPane().setContent(grid);

        Platform.runLater(() -> username.requestFocus());

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == loginButtonType) {
                return new Pair<>(username.getText(), password.getText());
            }
            return null;
        });

        Optional<Pair<String, String>> result = dialog.showAndWait();
        if (result.isPresent()) {
            compileList.getItems().add(result.get().getKey() + ":" + result.get().getValue());
        }
    });
    compileRemove.setOnAction((e) -> {
        if (compileList.getSelectionModel().getSelectedItem() != null) {
            compileList.getItems().remove(compileList.getSelectionModel().getSelectedItem());
        }
    });
    runtimeAdd.setOnAction((e) -> {
        TextInputDialog dia = new TextInputDialog();
        dia.setTitle("Add Runtime Argument");
        dia.setHeaderText("Enter an argument");
        dia.initOwner(stage);
        Optional<String> res = dia.showAndWait();
        if (res.isPresent()) {
            runtimeList.getItems().add(res.get());
        }
    });
    runtimeRemove.setOnAction((e) -> {
        if (runtimeList.getSelectionModel().getSelectedItem() != null) {
            runtimeList.getItems().remove(runtimeList.getSelectionModel().getSelectedItem());
        }
    });
    preview.setOnAction((e) -> {
        if (!iconField.getText().isEmpty()) {
            if (iconField.getText().endsWith(".ico")) {
                List<BufferedImage> read = new ArrayList<>();
                try {
                    read.addAll(ICODecoder.read(new File(iconField.getText())));
                } catch (IOException ex) {
                }
                if (read.size() >= 1) {
                    Image im = SwingFXUtils.toFXImage(read.get(0), null);
                    Stage st = new Stage();
                    st.initOwner(stage);
                    st.initModality(Modality.APPLICATION_MODAL);
                    st.setTitle("Icon Preview");
                    st.getIcons().add(Tachyon.icon);
                    st.setScene(new Scene(new BorderPane(new ImageView(im))));
                    if (applyCss.get()) {
                        st.getScene().getStylesheets().add(css);
                    }
                    st.showAndWait();
                }
            } else if (iconField.getText().endsWith(".icns")) {
                try {
                    BufferedImage ima = Imaging.getBufferedImage(new File(iconField.getText()));
                    if (ima != null) {
                        Image im = SwingFXUtils.toFXImage(ima, null);
                        Stage st = new Stage();
                        st.initOwner(stage);
                        st.initModality(Modality.APPLICATION_MODAL);
                        st.setTitle("Icon Preview");
                        st.getIcons().add(Tachyon.icon);
                        st.setScene(new Scene(new BorderPane(new ImageView(im))));
                        if (applyCss.get()) {
                            st.getScene().getStylesheets().add(css);
                        }
                        st.showAndWait();
                    }
                } catch (ImageReadException | IOException ex) {
                }
            } else {
                Image im = new Image(new File(iconField.getText()).toURI().toString());
                Stage st = new Stage();
                st.initOwner(stage);
                st.initModality(Modality.APPLICATION_MODAL);
                st.setTitle("Icon Preview");
                st.getIcons().add(Tachyon.icon);
                st.setScene(new Scene(new BorderPane(new ImageView(im))));
                if (applyCss.get()) {
                    st.getScene().getStylesheets().add(css);
                }
                st.showAndWait();
            }
        }
    });
    selectIm.setOnAction((e) -> {
        FileChooser fc = new FileChooser();
        fc.setTitle("Icon File");
        String OS = System.getProperty("os.name").toLowerCase();
        fc.getExtensionFilters().add(new ExtensionFilter("Icon File",
                OS.contains("win") ? getWindowsImageExtensions() : getMacImageExtensions()));
        fc.setSelectedExtensionFilter(fc.getExtensionFilters().get(0));
        File lf = fc.showOpenDialog(stage);
        if (lf != null) {
            iconField.setText(lf.getAbsolutePath());
        }
    });

    addJar.setOnAction((e) -> {
        FileChooser f = new FileChooser();
        f.setTitle("External Libraries");
        f.setSelectedExtensionFilter(new ExtensionFilter("Jar Files", "*.jar"));
        List<File> showOpenMultipleDialog = f.showOpenMultipleDialog(stage);
        if (showOpenMultipleDialog != null) {
            for (File fi : showOpenMultipleDialog) {
                if (!libsView.getItems().contains(fi.getAbsolutePath())) {
                    libsView.getItems().add(fi.getAbsolutePath());
                }
            }
        }
    });

    removeJar.setOnAction((e) -> {
        String selected = libsView.getSelectionModel().getSelectedItem();
        if (selected != null) {
            libsView.getItems().remove(selected);
        }
    });

    select.setOnAction((e) -> {
        List<String> all = getAll();
        ChoiceDialog<String> di = new ChoiceDialog<>(project.getMainClassName(), all);
        di.setTitle("Select Main Class");
        di.initOwner(stage);
        di.setHeaderText("Select A Main Class");
        Optional<String> show = di.showAndWait();
        if (show.isPresent()) {
            mainClass.setText(show.get());
        }
    });
    cancel.setOnAction((e) -> {
        stage.close();
    });
    confirm.setOnAction((e) -> {
        project.setMainClassName(mainClass.getText());
        project.setFileIconPath(iconField.getText());
        project.setRuntimeArguments(runtimeList.getItems());
        HashMap<String, String> al = new HashMap<>();
        for (String s : compileList.getItems()) {
            String[] spl = s.split(":");
            al.put(spl[0], spl[1]);
        }
        project.setCompileTimeArguments(al);
        project.setAllLibs(libsView.getItems());
        stage.close();
    });
}

From source file:tachyon.view.Viewer.java

private Image readFromFile(Path pr) {
    if (pr.toAbsolutePath().toString().endsWith(".ico")) {
        try {/*  w w w .  ja  v a2s.com*/
            return SwingFXUtils.toFXImage(ICODecoder.read(pr.toFile()).get(0), null);
        } catch (IOException ex) {
        }
    }
    if (pr.toAbsolutePath().toString().endsWith(".wbmp")) {
        try {
            return SwingFXUtils.toFXImage(ImageIO.read(pr.toFile()), null);
        } catch (IOException ex) {
        }
    }
    if (isValidFxImage(pr.toFile())) {
        try {
            //GIF, JPEG, PNG, BMP
            return new Image(pr.toUri().toString());
        } catch (Exception e) {
        }
    }
    try {
        //icns, cur, pcx, dcx, tiff, psd, xpm, xbm
        return SwingFXUtils.toFXImage(imageReadExample(pr.toFile()), null);
    } catch (ImageReadException | IOException ex) {
    }
    return null;
}

From source file:ui.main.MainViewController.java

private void addContactListener() {
    //this method adds a contacts list listener
    System.gc();//from   w  w w . j  av a2 s .  c om
    contacts.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue observable, Object oldValue, Object newValue) {
            if (newValue == null) {
                return;
            }
            conversations.getSelectionModel().clearSelection();
            chatList.getChildren().clear();
            isSingleChat = true;
            if (((RosterEntry) newValue).getType().equals(ItemType.from)) {
                friendRequest.setVisible(true);
            } else {
                friendRequest.setVisible(false);
            }
            Call.dialUser = ((RosterEntry) newValue).getUser();
            String chatterNameTem = ((RosterEntry) newValue).getUser(); //get reciever
            String chatterNameTem2 = chatterNameTem;

            ResultSet rs = DBSingleChat.readMessages(chatterNameTem); //load old messages

            chatterNameTem = chatterNameTem.substring(0, chatterNameTem.indexOf("@"));
            chatterNameTem = Character.toUpperCase(chatterNameTem.charAt(0)) + chatterNameTem.substring(1);

            chatterName.setText(chatterNameTem); //set chat box to recievers contacts
            currentChat = chatManager.createChat(((RosterEntry) newValue).getUser()); //set the current chat
            chatterPresence.setText(contactsManager.getPresence(((RosterEntry) newValue).getUser()));

            VCard vcard = new VCard(); //vcard to load presence
            try {
                vcard.load(connectionManager.getXMPPConnection(), currentChat.getParticipant());
                if (vcard.getAvatar() != null) {
                    BufferedImage img = ImageIO.read(new ByteArrayInputStream(vcard.getAvatar()));
                    Image image = SwingFXUtils.toFXImage(img, null);
                    chatterAvatar.setImage(image);
                } else {
                    chatterAvatar.setImage(defaultAvatar);
                }
            } catch (XMPPException ex) {
                chatterAvatar.setImage(defaultAvatar);
            } catch (IOException ex) {
                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NullPointerException ex) {
                chatterAvatar.setImage(defaultAvatar);
            } finally {
                chatterAvatar.setFitHeight(120);
                chatterAvatar.setFitWidth(100);
            }

            //display old messages -> current chat is required to be set as a prerequisit
            loadChat(chatterNameTem2);
            Task t = new Task() {
                @Override
                protected Object call() throws Exception {
                    Thread.sleep(500);
                    return new Object();
                }
            };

            t.setOnSucceeded(value -> scrollPane.setVvalue(scrollPane.getHmax()));

            Thread thread1 = new Thread(t);
            thread1.start();

            //show extra options
            showExtraComButtons();
        }
    });

}

From source file:ui.main.MainViewController.java

private synchronized void paintReceivedPhotoLoad(Chat chat, File recievedFile, String time) {
    //this method paints the recieved picture message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override//from  ww w  . j a  v  a 2 s .  c  om
        protected HBox call() throws Exception {
            Thread.sleep(100);
            VBox vbox = new VBox(); //to add text

            ImageView imageRec = new ImageView(chatterAvatar.getImage()); //image
            imageRec.setFitHeight(60);
            imageRec.setFitWidth(50);

            String strChatterName = chat.getParticipant(); //add name of the chatter with light color
            strChatterName = Character.toUpperCase(strChatterName.charAt(0))
                    + strChatterName.substring(1, strChatterName.indexOf("@"));
            Label chatterName = new Label(strChatterName);
            chatterName.setDisable(true);

            Label timeL = new Label(time);
            timeL.setDisable(true);
            timeL.setFont(new Font("Arial", 10));

            try {
                Image recievedImage = SwingFXUtils.toFXImage(ImageIO.read(recievedFile), null);
                ImageView receivedImageView = new ImageView(recievedImage);
                receivedImageView.setFitHeight(300);
                receivedImageView.setFitWidth(300);
                receivedImageView.setPreserveRatio(true);

                receivedImageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getButton() == MouseButton.PRIMARY) {
                            Desktop dt = Desktop.getDesktop();
                            try {
                                dt.open(recievedFile);
                            } catch (IOException ex) {
                                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null,
                                        ex);
                            }
                        }
                    }
                });

                receivedImageView.setOnMouseEntered(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.HAND);
                    }
                });

                receivedImageView.setOnMouseExited(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.DEFAULT);
                    }
                });

                vbox.getChildren().addAll(chatterName, receivedImageView, timeL);
            } catch (IOException e) {
                e.printStackTrace();
            }
            vbox.setAlignment(Pos.CENTER_RIGHT);
            HBox hbox = new HBox();
            //bbl.setBubbleSpec(BubbleSpec.FACE_LEFT_CENTER);
            hbox.getChildren().addAll(imageRec, vbox);
            return hbox;
        }
    };

    recievedMessages.setOnSucceeded(event -> {
        chatList.getChildren().add(recievedMessages.getValue());
    });

    if (chat.getParticipant().contains(currentChat.getParticipant())) {
        Thread t = new Thread(recievedMessages);
        t.start();
        try {
            t.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:ui.main.MainViewController.java

private synchronized void paintReceivedPhotoOnTransmit(Chat chat, File recievedFile, String time) {
    //this method paints the recieved picture message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*  w ww .j ava  2 s .c  o m*/
        protected HBox call() throws Exception {
            VBox vbox = new VBox(); //to add text
            Thread.sleep(2000);
            ImageView imageRec = new ImageView(chatterAvatar.getImage()); //image
            imageRec.setFitHeight(60);
            imageRec.setFitWidth(50);

            String strChatterName = chat.getParticipant(); //add name of the chatter with light color
            strChatterName = Character.toUpperCase(strChatterName.charAt(0))
                    + strChatterName.substring(1, strChatterName.indexOf("@"));
            Label chatterName = new Label(strChatterName);
            chatterName.setDisable(true);

            Label timeL = new Label(time);
            timeL.setDisable(true);
            timeL.setFont(new Font("Arial", 10));

            try {
                Image recievedImage = SwingFXUtils.toFXImage(ImageIO.read(recievedFile), null);
                ImageView receivedImageView = new ImageView(recievedImage);
                receivedImageView.setFitHeight(300);
                receivedImageView.setFitWidth(300);
                receivedImageView.setPreserveRatio(true);

                receivedImageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getButton() == MouseButton.PRIMARY) {
                            Desktop dt = Desktop.getDesktop();
                            try {
                                dt.open(recievedFile);
                            } catch (IOException ex) {
                                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null,
                                        ex);
                            }
                        }
                    }
                });

                receivedImageView.setOnMouseEntered(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.HAND);
                    }
                });

                receivedImageView.setOnMouseExited(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.DEFAULT);
                    }
                });

                vbox.getChildren().addAll(chatterName, receivedImageView, timeL);
            } catch (IOException e) {
                e.printStackTrace();
            }
            vbox.setAlignment(Pos.CENTER_RIGHT);
            HBox hbox = new HBox();
            hbox.getChildren().addAll(imageRec, vbox);
            return hbox;
        }
    };

    recievedMessages.setOnSucceeded(event -> {
        chatList.getChildren().add(recievedMessages.getValue());
    });
    //set the received chat message appear on the screen
    if (chat.getParticipant().contains(currentChat.getParticipant())) {
        Thread t = new Thread(recievedMessages);
        t.start();
    }
    Task t = new Task() {
        @Override
        protected Object call() throws Exception {
            Thread.sleep(2500);
            return new Object();
        }
    };

    t.setOnSucceeded(value -> scrollPane.setVvalue(scrollPane.getHmax()));

    Thread thread1 = new Thread(t);
    thread1.start();
}

From source file:ui.main.MainViewController.java

private synchronized void paintSentPhoto(Chat chat, File file, String time) {
    //this method paints the recieved picture message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override/*from  w  w w.j  av a  2s.  co  m*/
        protected HBox call() throws Exception {
            //                Thread.sleep(100);
            VBox vbox = new VBox(); //to add text

            ImageView imageRec = new ImageView(myAvatar.getImage()); //image
            imageRec.setFitHeight(60);
            imageRec.setFitWidth(50);

            Label chatterName = new Label(name.getText());
            chatterName.setDisable(true);

            Label timeL = new Label(time);
            timeL.setDisable(true);
            timeL.setFont(new Font("Arial", 10));

            try {
                Image recievedImage = SwingFXUtils.toFXImage(ImageIO.read(file), null);
                ImageView receivedImageView = new ImageView(recievedImage);
                receivedImageView.setFitHeight(300);
                receivedImageView.setFitWidth(300);
                receivedImageView.setPreserveRatio(true);

                receivedImageView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        if (event.getButton() == MouseButton.PRIMARY) {
                            Desktop dt = Desktop.getDesktop();
                            try {
                                dt.open(file);
                            } catch (IOException ex) {
                                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null,
                                        ex);
                            }
                        }
                    }
                });

                receivedImageView.setOnMouseEntered(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.HAND);
                    }
                });

                receivedImageView.setOnMouseExited(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        chatList.getScene().setCursor(Cursor.DEFAULT);
                    }
                });

                vbox.getChildren().addAll(chatterName, receivedImageView, timeL);
            } catch (IOException e) {
                e.printStackTrace();
            }
            vbox.setAlignment(Pos.CENTER_LEFT);
            HBox hbox = new HBox();
            hbox.setAlignment(Pos.CENTER_RIGHT);
            //bbl.setBubbleSpec(BubbleSpec.FACE_LEFT_CENTER);
            hbox.getChildren().addAll(vbox, imageRec);
            return hbox;
        }
    };

    recievedMessages.setOnSucceeded(event -> {
        chatList.getChildren().add(recievedMessages.getValue());
    });

    if (chat.getParticipant().contains(currentChat.getParticipant())) {
        Thread t = new Thread(recievedMessages);
        t.start();
        try {
            t.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:ui.main.MainViewController.java

private void paintConversationMessage(Message msg) {
    //this method draws the recievied text message
    Task<HBox> recievedMessages = new Task<HBox>() {
        @Override//  w w w.j  av  a 2 s .  c o m
        protected HBox call() throws Exception {

            VBox vbox = new VBox(); //to add text
            String user = msg.getFrom();
            user = user.substring(user.indexOf("/") + 1, user.length());
            ImageView imageView = new ImageView(); //image
            imageView.setFitHeight(60);
            imageView.setFitWidth(50);
            VCard vcard = new VCard();
            try {
                vcard.load(ConnectionManager.getConnectionManager().getXMPPConnection(),
                        user.concat(AppData.serviceNameAt));
                if (vcard.getAvatar() != null) {
                    BufferedImage img = ImageIO.read(new ByteArrayInputStream(vcard.getAvatar()));
                    Image image = SwingFXUtils.toFXImage(img, null);
                    imageView.setImage(image);
                } else {
                    Image defaultAvatar = new Image("resources/defaultAvatar.png", 50, 60, true, true);
                    imageView.setImage(defaultAvatar);
                }
            } catch (XMPPException e) {
                Image defaultAvatar = new Image("resources/defaultAvatar.png", 50, 60, true, true);
                imageView.setImage(defaultAvatar);
                System.out.println(e);
            }

            Label chatterName = new Label(user);
            chatterName.setDisable(true);

            //chat message
            BubbledLabel bbl = new BubbledLabel();
            bbl.setText(msg.getBody());
            bbl.setBackground(new Background(new BackgroundFill(Color.GAINSBORO, null, null)));

            vbox.getChildren().addAll(chatterName, bbl);
            vbox.setAlignment(Pos.CENTER_RIGHT);
            HBox hbox = new HBox();
            bbl.setBubbleSpec(BubbleSpec.FACE_LEFT_CENTER);
            hbox.getChildren().addAll(imageView, vbox);
            return hbox;
        }
    };

    recievedMessages.setOnSucceeded(event -> {
        chatList.getChildren().add(recievedMessages.getValue());

    });

    Thread t = new Thread(recievedMessages);
    //t.setDaemon(true);
    t.start();
    try {
        t.join();
    } catch (InterruptedException ex) {
        Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
    }
    Task t1 = new Task() {
        @Override
        protected Object call() throws Exception {
            Thread.sleep(500);
            return new Object();
        }
    };

    t1.setOnSucceeded(value -> scrollPane.setVvalue(scrollPane.getHmax()));

    Thread thread1 = new Thread(t1);
    thread1.start();
}