I have to copy the chosen image to the application folder. The image will be chosen by clicking the button. Here is the code (ActionListener) for that Button
imageButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String outPath = new java.io.File("").getAbsolutePath();
fileChooser.showOpenDialog(null);
File pic = fileChooser.getSelectedFile();
String inPath = pic.getPath();
try {
Utils.copyFile(inPath, outPath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
The method copyFile is this:
public static void copyFile(String inPath, String outPath) throws IOException
{
FileInputStream fis=new FileInputStream(new File(inPath));
FileOutputStream fos=new FileOutputStream(new File(outPath));
int c;
while((c=fis.read())!=-1)
{
fos.write(c);
}
}
It gives "File not Found Exception" in Blue and in red color it shows "Access is Denied" when i select the image. I am not sure where the problem is there in my code.
Related
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);
}
runEncrypt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File inputFile = new File("/Users/aktasberk/Desktop/hey");
File encryptedFile = new File("/Users/aktasberk/Desktop/Encrypted_"+inputFile.getName());
File decryptedFile = new File("/Users/aktasberk/Desktop/Decrypted_"+inputFile.getName());
try {
String key = "16BitKeyIsHere16";
CryptoUtils.encrypt(key, inputFile, encryptedFile);
CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
} catch (CryptoException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
});
Okay so I have an encryption&decryption project, the encrypting and decrypting works fine but I have some problems using FileInputStream to get the file from directory, I have a browse button to do that but could not make it work, so as you can see in the code I get the input file manually.
Below here is my browse button opening up a file dialog to let me choose a file.
browseEncrypt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File selectedFile = chooseEncrypt.showOpenDialog(primaryStage);
if (selectedFile != null) {
encryptPath.setText(selectedFile.getPath());
primaryStage.show();
}
}
});
I need to get the file from browse button instead of declaring it manually in the code, I can be more specific if info is needed, thanks.
Delete local:
File encryptedFile = new File("/Users/aktasberk/Desktop/Encrypted_"+inputFile.getName());
Make global
File encryptedFile;
Then:
browseEncrypt.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
File selectedFile = chooseEncrypt.showOpenDialog(primaryStage);
if (selectedFile != null) {
encryptPath.setText(selectedFile.getPath());
encryptedFile = selectedFile;//Add This!
primaryStage.show();//Not sure why this is here?
}
}
});
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");
}
});
I'm using Eclipse saving a .wav file and roughly every fourth or fifth time I run the program it saves the file fine. Most times the program itself just hangs and the screen goes black when the file chooser frame should become visible to choose the location of the file. Does anyone know why this would happen occasionally? Eclipse gives no error in the console window and the code builds fine with no errors.
StopRecording and saveFile are are in the Mainframe class
save method is in another recording setup class
private void stopRecording() {
isRecording = false;
try {
timer.cancel();
RecordButton.setText("Record");
RecordButton.setIcon(iconRecord);
recorder.stop();
saveFile();
} catch (IOException ex) {
JOptionPane.showMessageDialog(Mainframe.this, "Error",
"Error stopping sound recording!",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
private void saveFile() {
JFileChooser fileChooser = new JFileChooser();
FileFilter wavFilter = new FileFilter() {
#Override
public String getDescription() {
return "Sound file (*.WAV)";
}
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
return file.getName().toLowerCase().endsWith(".wav");
}
}
};
fileChooser.setFileFilter(wavFilter);
fileChooser.setAcceptAllFileFilterUsed(false);
int userChoice = fileChooser.showSaveDialog(this);
if (userChoice == JFileChooser.APPROVE_OPTION) {
saveFilePath = fileChooser.getSelectedFile().getAbsolutePath();
if (!saveFilePath.toLowerCase().endsWith(".wav")) {
saveFilePath += ".wav";
}
File wavFile = new File(saveFilePath);
try {
recorder.save(wavFile);
buttonPlay.setEnabled(true);
Keyup.setEnabled(true);
Keydown.setEnabled(true);
btnSave.setEnabled(true);
getKey.setEnabled(true);
System.out.print(saveFilePath);
} catch (IOException ex) {
JOptionPane.showMessageDialog(Mainframe.this, "Error",
"Error saving to sound file!",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
public void save(File wavFile) throws IOException {
byte[] audioData = recordBytes.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(audioData);
AudioInputStream audioInputStream = new AudioInputStream(bais, format,
audioData.length / format.getFrameSize());
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, wavFile);
audioInputStream.close();
recordBytes.close();
}
You are calling recorder.save(wavFile); twice. Try calling it just once.
I've got what seems like a very simple section of code, and I can't work out for the life of me why it's not working.
I have a method that listens for image updates from a camera and when it recieves them it calls another segment of code.
My listener is:
public void imageUpdated(BufferedImage image) {
if (null != video) {
video.setImage(image);
}
File outputfile = new File("savedingui.jpg");
try {
ImageIO.write(image, "jpg", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
Which happily saves the correct image to disc. However when I save the image again from the setImage method (called on line 3 of the listener code)
public void setImage(BufferedImage image) {
File outputfile = new File("savedorig.jpg");
try {
ImageIO.write(image, "jpg", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
It now just saves a jpeg of black. But the right sized square of black.
Any clues as to whats going on?
I can not reproduce your issue with the following source (which is basically copied from your question):
public static void imageUpdated(BufferedImage image) {
setImage(image);
File outputfile = new File("savedingui.jpg");
try {
ImageIO.write(image, "jpg", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void setImage(BufferedImage image) {
File outputfile = new File("savedorig.jpg");
try {
ImageIO.write(image, "jpg", outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
BufferedImage image = ImageIO.read(new File("test.jpg"));
imageUpdated(image);
}
Is the same instance used somewhere else, e.g. camera writing updated data in it?