how to upload and display image in JFrame using JFileChooser - java

I need to upload and display an image selected with the JFileChooser (i.e the user wants to set his/her profile picture) in a JFrame.. How should I do it?
Here is my code for choosing the file:
private void UploadImageActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChosser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChosser.getSelectedFile();
// What to do with the file
// I want code for this part
try {
//code that might create an exception
}
catch (Exception e1) {
e.printStackTrace();
}
}
}

I solved it myself. I chose an image and displayed in a JLabel.
Here is My code:
private void uploadImageActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your File");
filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// below code selects the file
int returnval = filechooser.showOpenDialog(this);
if (returnval == JFileChooser.APPROVE_OPTION)
{
File file = filechooser.getSelectedFile();
BufferedImage bi;
try {
// display the image in a Jlabel
bi = ImageIO.read(file);
jLabel1.setIcon(new ImageIcon(bi));
} catch(IOException e) {
e.printStackTrace(); // todo: implement proper error handeling
}
this.pack();
}
}

Related

How To Open File Dialog And Create File On It?

1
I opened File Dialog but I don't create the file on it? How?
JFileChooser fileChooser = new JFileChooser();
File selectedFile = null;
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (**result == JFileChooser.APPROVE_OPTION**) {
selectedFile = fileChooser.getSelectedFile();
} else {
confirmExit();
return;
}
To save a file with JFileChooser, you need to use the showSaveDialog() method instead of the showOpenDialog() like in your snippet. For more information check out How to use File Choosers and check out the JFileChooser JavaDoc.
Then the next step if the saving has been approved, is to actually write the file.
For this, you can use a FileWriter.
I put together a small snippet, which opens a JFileChooser on a button click, where you can provide the filename, where some String will be written to this file.
Example:
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> buildGui());
}
private static void buildGui() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton btn = new JButton("Save your File");
// action listener for the button
btn.addActionListener(e -> {
JFileChooser fileChooser = new JFileChooser(); // create filechooser
int retVal = fileChooser.showSaveDialog(frame); // open the save dialog
if (retVal == JFileChooser.APPROVE_OPTION) { // check for approval
// create a bufferedwriter with the specified file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()))) {
// write the content to the file
writer.write("Your content that shall be written to the file");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
panel.add(btn);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Output:

How can I fix my code so that it contains both a "save" and "save as" functions?

I have two buttons in a menubar that contains both a save and save as button. However, I currently have the code for both of them the same and it does the save as currently with prompting the user where they want to save. I want the save button to only save without prompting for the dialog unless the file doesn't yet exist.
I've tried fiddling around with the code to try and figure out a workaround, but have not figure it out.
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
The code currently does the exact same save function for each save button. I want it to only prompt for the save as button.
You need to have a File instance field in your class that is initially assigned to null. When you read in a File or when you do your first save, then this field is assigned to that File. When the save button is pressed, then you check if the field is null, and if so, show the dialog as you would for the save-as button. If the field is not null, then you simply write the file to disk using the data that you have and that File.
for example (code not tested):
// a private instance field
private File myFile = null;
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (myFile == null) {
saveAs();
} else {
writeFile(myFile);
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
saveAs();
}
});
private void writeFile(File file) {
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
private void saveAs() {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
myFile = file; // !!
writeFile(file);
}

Image didn't load in JPanel

I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.
This is the action event for the browseBtn
private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
JLabel l = new JLabel(image);
imagePanel.add(l);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.
You should avoid creating new objects everytime you want to display your image, imagine if you change it 5 times, you're creating 5 times an object while you display only one !
Like said in the comments, your best shot would be to create your label when you create your panel, add it to said panel, then simply change the icon of this label when you load your image.
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
label.setIcon(image);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});
Assuming label is the reference to said JLabel, created on components initialisation.
Or you might try this :
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon imageIcon = new ImageIcon(new ImageIcon(file.getPath()).getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)); //resizing
label.setIcon(imageIcon);
/*try { // or try this
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(file.getPath());
BufferedImage img = ImageIO.read(inStream);
Image rimg = img.getScaledInstance(width, height, Image.SCALE_STANDARD);
label.setIcon(rimg);
} catch (IOException e) {}*/
} catch (Exception ex) {JOptionPane.showMessageDialog(this, "Error reading file !");}
} else {JOptionPane.showMessageDialog(this, "Choose png file only !");}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});

Java Netbeans Absolute Path

I created a text editor and a Save button, i need to create an absolute finder so that if the user does not enter .txt the program will automatically do it so it always saves as txt file. Some help pls?
Code for my save button
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooseFile = new JFileChooser();
int choosing = chooseFile.showSaveDialog(this);
if ( choosing == JFileChooser.APPROVE_OPTION)
{
try {
PrintWriter fileSave = new PrintWriter(chooseFile.getSelectedFile());
//absolute path ends with
fileSave.printf(txtArea.getText());
fileSave.close();
txtStatus.setText("Saved");
} catch (FileNotFoundException ex) {
Logger.getLogger(TextEditor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
import org.apache.commons.io.FilenameUtils;
File f= chooseFile.getSelectedFile();
String filePath=f.getAbsolutePath();
if(!filePath.endsWith("txt")){
if(FilenameUtils.indexOfExtension(filePath)==-1){//user has other provided extension
filePath+=".txt";
}
}

How to save Icon object into a file via JFileChooser?

I have a JLabel inside which I have saved my ImageIcon like this:
ImageIcon imageIcon = sample.map(); // a map method create an ImageIcon object
imageLabel.setIcon(imageIcon);
imageLabel.setVisible(true);
Now I would like to save this ImageIcon object into a PNG file when clicking on the Save item menu.
private void imageActionPerformed(java.awt.event.ActionEvent evt) {
Icon pic = imageLabel.getIcon();
JFileChooser fileChooser = new JFileChooser("C:/");
fileChooser.setSelectedFile(file);
// this filter will allow just PNG extension
FileFilter filter = new MyCustomFilter2();
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File fileToSave = fileChooser.getSelectedFile();
}
else
{
System.out.println("File access cancelled by user.");
}
}
Yes I know that this code is wrong and some part is missing, I think I should somehow save my Icon object called pic into a File object. This is my assumption. How can I do it please?
Thanks for any help,
Michal.
Here is my source code
private void imageActionPerformed(java.awt.event.ActionEvent evt) {
try{
Icon image = imageLabel.getIcon();
BufferedImage bi = new BufferedImage(image.getIconWidth(),image.getIconHeight(),BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
File file = new File("outputFile");
JFileChooser fileChooser = new JFileChooser("C:/");
fileChooser.setSelectedFile(file);
FileFilter filter = new MyCustomFilter2();
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
ImageIO.write(bi, "PNG", file);
File fileToSave = fileChooser.getSelectedFile();
}
else
{
System.out.println("File access cancelled by user.");
}
}
catch(IOException e){
e.printStackTrace();
}
}
The File object returned by the JFileChooser just represents the location on disk where the user would like to save the file. After that you'll want to use ImageIO.write() to save the file to disk.
e.g.
ImageIO.write(image, "png", file);
If you have an Icon, I think you may need to convert that to a BufferedImage before you can save it.

Categories