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();
Related
My goal is to display images that are selected from a filechooser activated by button, and add those images to my gridpane. I am able to get the right URL file path name from the file chooser in order to make a correct imageview however when doing so my gridpane does not show any images being added..
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();
String megaUrl;
try {
megaUrl = Paths.get(megaPath).toUri().toURL().toString();
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
parentPath = selectedFile.getParent();
System.out.println("wholePath: " + wholePath);
System.out.println("parent: " + parentPath);
System.out.println("File Name: " + name);
System.out.println("megaPath: " + megaUrl);
//System.out.println("Canonical: " + Canonical);
Image newAwesomeImage = new Image(megaUrl);
paneofgridmonkeys.add(new ImageView(newAwesomeImage), 0, 0);
//ImageView view = new ImageView();
//view.setImage(newAwesomeImage);
//paneofgridmonkeys.add(view, 1, 1);
//paneofgridmonkeys.setConstraints(view, 0, 4);
//paneofgridmonkeys.add(new Label("Changed the image!"), 0, 1);
createDisplay(primaryStage);
}
}
});
}
I've tried multiple ways of insterting an images and these are the filepaths im getting:
wholePath: \\jupiter\yr1005\Desktop\20190111_1340501.jpg
parent: \\jupiter\yr1005\Desktop
File Name: 20190111_1340501.jpg
megaPath: file://jupiter/yr1005/Desktop/20190111_1340501.jpg
(im using the megapath)
basically when i choose an image from filechooser I get no error but no image is shown after selection. I just get all the print statements in return.. an idea why?
This is my create Display method:
public void createDisplay(Stage primaryStage) {
primaryStage.setTitle(this.MONKEY_TITLE);
GridPane paneofgridmonkeys = new GridPane();
paneofgridmonkeys.setAlignment(Pos.CENTER);
paneofgridmonkeys.setVgap(10);
paneofgridmonkeys.add(browseButton, 10, 10);
ScrollPane allTehFaces = new ScrollPane(paneofgridmonkeys);
allTehFaces.setFitToWidth(true);
primaryStage.setScene(new Scene(allTehFaces, 500, 500));primaryStage.show();
}
}
You're problem is in the createDisplay method; specifically this line:
GridPane paneofgridmonkeys = new GridPane();
Here you're creating a locally-scoped GridPane called paneofgridmonkeys, which must be the name of another class-level variable called paneofgridmonkeys, since it's available to makeBrowseButton. When you do this in local scope, the new instance you've created becomes the one that's used inside of that method, rather than the class-level instance; thus the class-level one isn't the one being added to your scene, and you're not seeing the changes.
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.
I created a browse button and here is the code for that:
private void lookForExeClick () throws FileNotFoundException{
DirectoryDialog dlg = new DirectoryDialog(Display.getCurrent().getActiveShell());
String directoryPath = dlg.open();
//File file = new File(directoryPath, "MyFileName.txt");
//FileOutputStream outputStream = new FileOutputStream(file);
My text box that I created on the gui is this:
exeLocationText = new Text(controlGroupForSingleRun, SWT.BORDER);
exeLocationText.setText("");
data = new GridData();
data.widthHint = 265;
exeLocationText.setLayoutData(data);
How do I get the filepath that I choose in the directory dialog box after I click browse into the text box that I created in java. Any advice would be helpful. Thanks.
In your click handler, you would just have:
String directoryPath = dlg.open();
if(directoryPath != null)
exeLocationText.setText(directoryPath);
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);
}
}
}
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());
}
}
});