how to insert a picture using file chooser - java

I'm creating a program to register employees, and was wondering how to put a picture of the employees registered When do your record. I would use a button to select this file and attach the photo along with your registration? But how would this be done using JavaFX? Thank you!!

I managed as follows:
#FXML
private void searchPicture(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
File file = fileChooser.showOpenDialog(new Stage());
if (file != null) {
Image img = new Image(file.toURI().toString());
imagem.setImage(img);
imagem.setFitWidth(171);
imagem.setFitHeight(176);
imagem.setPreserveRatio(false);
}
}
}

Related

java.lang.IllegalArgumentException: Invalid URL: unknown protocol: m / filechooser path problem [duplicate]

This question already has answers here:
How to load Image file to ImageView?
(3 answers)
Closed 3 years ago.
I am trying to add an image to a gridview using a button that opens up a filechooser that only accepts images. I am getting an exception error when im using the file path from the filechooser to create a setImage to my grid view. I think this is because the path im getting is just not right.
Here is the code where it fails:
public void makeBrowseButton(Stage primaryStage) {
//attach handler
browseButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser fileChooser = new FileChooser(); // create object
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")); //filter for music files
//FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
if ( !parentPath.equalsIgnoreCase("")) { //go to previous directory if exists
File parentPathFile = new File(parentPath);
fileChooser.setInitialDirectory(parentPathFile);
}
File selectedFile = fileChooser.showOpenDialog(primaryStage);
if (selectedFile != null) { // display the dialog box
String wholePath = selectedFile.getPath();
String name = selectedFile.getName();
String megaPath = selectedFile.getAbsolutePath();
parentPath = selectedFile.getParent();
System.out.println("wholePath: " + wholePath);
System.out.println("File Name: " + name);
System.out.println("megaPath: " + megaPath);
Image newAwesomeImage = new Image(megaPath);
ImageView view = new ImageView();
view.setImage(newAwesomeImage);
paneofgridmonkeys.add(view, 0, 0);
//paneofgridmonkeys.add(new Label("Changed the image!"), 0, 1);
createDisplay(primaryStage);
}}});
}
The error message is the title it is saying that the exact problem is line:
view.setImage(newAwesomeImage);
as for my system.out results this is what im getting:
wholePath: M:\Home\BenStillerDuckFace.jpg
File Name: BenStillerDuckFace.jpg
megaPath: M:\Home\BenStillerDuckFace.jpg
ive tried all of these and non work. Any ideas?
The Image(String url) constructor requires a URL string, not a file name. A file name is not a URL.
To convert a file name string to a URL string, do one of these:
// Java 7+
String megaUrl = Paths.get(megaPath).toUri().toURL().toString();
// Java 1.4+
String megaUrl = new File(megaPath).toURI().toURL().toString();

copy an image to localhost/images

I'm working in a desktop application using javafx.
This is my code. The method telechargerImage() is called when the user clicks on the button uploadimage in order to choose an image and then I want to save it in localhost/images.
Excuse my english.
private Image imagelog;
#FXML
private ImageView image;
#FXML
private JFXButton uploadimage;
private FileChooser fileChooser = new FileChooser();
private File file = null;
void telechargerImage(ActionEvent event) {
File file = fileChooser.showOpenDialog(stage);
if (file != null) {
imagelog = new Image(file.toURI().toString());
image.setImage(imagelog);
}
}

How to open a PDF file javafx

I want to open a pdf file and display it on new window when a button is clicked
i try this an it is not working:
Button btn = new Button();
File file=new File("Desktop/Test.pdf");
btn.setText("Open");
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Exemple.class.getName())
.log(Level.SEVERE, null, ex);
}
}
});
You can try this way to open a PDF file:
File file = new File("C:/Users/YourUsername/Desktop/Test.pdf");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
If you want to use FileChooser, then use this:
btn.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
FileChooser fileChooser = new FileChooser();
// Set Initial Directory to Desktop
fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "\\Desktop"));
// Set extension filter, only PDF files will be shown
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PDF files (*.pdf)", "*.pdf");
fileChooser.getExtensionFilters().add(extFilter);
// Show open file dialog
File file = fileChooser.showOpenDialog(primaryStage);
//Open PDF file
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
}
});
If you are using windows you need to fix the path of the file like this:
File file=new File("C:\\Users\\USER\\Desktop\\Test.pdf");
You need to change USER with your windows user.
Also, note that \ is used for escape sequences in programming languages.

JavaFX- MediaView not displaying the video

I have a MediaView on the scene in which I am trying to play the selected video. The video is playing, I can hear the sound, but it's not visible.
here's my code:
playLocalVideo.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File fileToPlay = null;
//DirectoryChooser directoryChooser = new DirectoryChooser();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Files to Upload");
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("VIDEO files (*.mp4)", "*.mp4");
fileChooser.getExtensionFilters().add(extFilter);
fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
try {
fileToPlay = fileChooser.showOpenDialog(stage).getCanonicalFile();
Media m = new Media(fileToPlay.toURI().toString());
MediaPlayer mp = new MediaPlayer(m);
videoPlayer = new MediaView(mp);
videoPlayer.setPreserveRatio(true);
mp.play();
} catch (IOException ex) {
Logger.getLogger(TutorControlPanelController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
Sorted:
instead of:
videoPlayer = new MediaView(mp);
You should do:
videoPlayer.setMediaPlayer(mp);
I had the same issue that audio is playing but no video is playing when MP4 file used code MPEG-4. After I changed the codec to H.264 the video became playing correct.

Java: JFileChooser How to show Selected File in a textField

I have a JFileChooser and Im able to print the Absolute Path in console.
I need to show the FilePath in a Text field as soon as the User selects the file.
Below is the code please let me know how to do it.
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int showOpenDialog = fileChooser.showOpenDialog(frame);
if (showOpenDialog != JFileChooser.APPROVE_OPTION) return;
Please let me know if you need any other details.
You need to listen to the changes that occur when using the JFileChooser, see this snipet of code:
JFileChooser chooser = new JFileChooser();
// Add listener on chooser to detect changes to selected file
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY
.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser)evt.getSource();
File oldFile = (File)evt.getOldValue();
File newFile = (File)evt.getNewValue();
// The selected file should always be the same as newFile
File curFile = chooser.getSelectedFile();
} else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(
evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser)evt.getSource();
File[] oldFiles = (File[])evt.getOldValue();
File[] newFiles = (File[])evt.getNewValue();
// Get list of selected files
// The selected files should always be the same as newFiles
File[] files = chooser.getSelectedFiles();
}
}
}) ;
All you need to do inside the first condition is set the value of your textfield to match the new selected filename. See this example:
yourTextfield.setText(chooser.getSelectedFile().getName());
Or just
yourTextfield.setText(curFile.getName());
It is the method getName() from class File that will give you what you need.
Help your self from de API docs to see what each method does.
You can use this code to show the path in a text field.
if(fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
using what Genhis has said, please see the full code block you can use to get a 'browse' button to place the file path in a correlating JTextField.
JButton btnNewButton = new JButton("Browse");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File("C:/Users"));
fc.setDialogTitle("File Browser.");
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (fc.showOpenDialog(btnNewButton) == JFileChooser.APPROVE_OPTION){
textField.setText(fc.getSelectedFile().getAbsolutePath());
}
}
});

Categories

Resources