File saved with JFileChooser showSaveDialog even on 'Cancel' - java

I have a file saved that works fine apart from one problem. When the cancel button is pressed a copy of the file is saved in the java directory. This only happens when the cancel button is pressed, if the save button is used the file ends up where the user selects. How can I stop this happening so when the cancel button is pressed nothing is saved anywhere?
My code is below, all help appreciated. Thanks
// Save dialog
private void savePlaylist() {
JFileChooser savePlaylistDialog = new JFileChooser();
savePlaylistDialog.setSelectedFile(new File(newPlaylistNameTxt.getText() + ".txt"));
savePlaylistDialog.showSaveDialog(playlistDialogs);
File savePlaylist = savePlaylistDialog.getSelectedFile();
try {
outFile = new PrintWriter(new FileWriter(savePlaylist));
outFile.println(newPlaylistInformationTxt.getText());
outFile.close();
// Plays a sound when play() is called (edited from Bombard)
try {
Clip saveButtonSound = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("Tri-tone.wav"));
saveButtonSound.open(ais);
saveButtonSound.start();
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "File could not be written, try again.");
}
}

savePlaylistDialog.showSaveDialog(playlistDialogs);
That method call above returns an int. You need to check its value - if the user clicked on the Save button, it would return JFileChooser.ACCEPTED_OPTION. In this case, you are taking the return value (which could be accepted/save or cancel), ignoring it, and proceeding to write the data to disk anyway.

Here is the fixed code I used:
// Save dialog
private void savePlaylist() {
JFileChooser savePlaylistDialog = new JFileChooser();
savePlaylistDialog.setSelectedFile(new File(newPlaylistNameTxt.getText() + ".txt"));
int status = savePlaylistDialog.showSaveDialog(playlistDialogs);
try {
if (status == JFileChooser.APPROVE_OPTION) {
//User has pressed save button
File savePlaylist = savePlaylistDialog.getSelectedFile();
outFile = new PrintWriter(new FileWriter(savePlaylist));
outFile.println(newPlaylistInformationTxt.getText());
outFile.close();
// Plays a sound when play() is called (edited from Bombard)
try {
Clip saveButtonSound = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("Tri-tone.wav"));
saveButtonSound.open(ais);
saveButtonSound.start();
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (status == JFileChooser.CANCEL_OPTION) {
// User has pressed cancel button
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "File could not be written, try again.");
}
}

showSaveDialog should return whether the user canceled or not and you code shoul act accordingly. At the moment you save no matter what the user did in the save dialog.

Related

Save voice from text to speech into audio file using JFileChooser

I am using FreeTTS voice in my project for tts.
I want to save the voice to an audio file using JFileChooser to any location which user wants. I want to add a button which saves the audio file.Till now i have a "Open File" which opens text file and writes it into the JTextArea and a "Save File" button which saves the text written in JTextArea to output file in txt format.I am using NetBeans for the project.
The screenshot of the java application
// Code for Saving Text File
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser saver = new JFileChooser("./");
int returnVal = saver.showSaveDialog(this);
File file = saver.getSelectedFile();
BufferedWriter writer = null;
if (returnVal == JFileChooser.APPROVE_OPTION)
{
try
{
writer = new BufferedWriter( new FileWriter(file.getAbsolutePath()+".txt"));
writer.write(jTextArea1.getText());
writer.close( );
JOptionPane.showMessageDialog(this, "The Message was Saved Successfully!",
"Success!", JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, "The Text could not be Saved!",
"Error!", JOptionPane.INFORMATION_MESSAGE);
}
}
}
//Code tried for saving audio file but did not worked
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser saver = new JFileChooser("./");
int returnVal = saver.showSaveDialog(this);
File file = saver.getSelectedFile();
VoiceManager voiceManager = VoiceManager.getInstance();
Voice saveVoice = voiceManager.getVoice(VOICENAME);
saveVoice.allocate();
if (returnVal == JFileChooser.APPROVE_OPTION)
{
try {
audioPlayer = new SingleFileAudioPlayer(new FileWriter( file.getAbsolutePath()+AudioFileFormat.Type.WAVE));
saveVoice.setAudioPlayer(audioPlayer);
saveVoice.speak(jTextArea1.getText());
saveVoice.deallocate();
audioPlayer.close();
JOptionPane.showMessageDialog(this, "The Audio was Saved Successfully!",
"Success!", JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, "The Text could not be Saved!",
"Error!", JOptionPane.INFORMATION_MESSAGE);
}
}
}
Similarly the code for the Opening text file is there.
I don't have much reputation that why i am not able to add screenshot directly but i have added the link to it.
An object of SingleFileAudioPlayer set as the audio player for the freetts voice can be used to write to a file.
You can find the solution on this question: how can i store output voice to an audio file in freetts

Why does my java program occasionally not respond saving a file with java filechooser?

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.

JAVA - Boolean correction - Still going on when pressing Play

So im pretty close to my end and I can't figure out why its doing like this. Maybe because im stupid right now after coding a while. however. So I have two files that should be allowed to my program. The first one is a MP3 and the Other one is Wav. I got them to work. By that I mean if I choose Wav file, the sound comes, if I choose the mp3 it works so there is no problem with that but the problem is right now is when pressing Open (-> browersing a file) and then press play, the sound should come, and yes it does. so when I open a another file for exemple a new song. then press play. the song is playing with the first song which makes it two tracks at the same time and I want it to make -> when one song is playing then play. and if I choose new song and press play, then the first song should go away. I think im pretty close but yeah. However I have done this
static boolean status = true;
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnPlay) {
if(!status) {
clip.start();
lblPlaying.setText("Enjoy the music!");
} else if(status == true) {
mp3_player.play();
lblPlaying.setText("Enjoy the music!");
}
}
}
});
public void Choose() throws IOException {
String userDir = System.getProperty("user.home");
JFileChooser fileChooser = new JFileChooser(userDir +"/Desktop");
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
String ext = selectedFile.getPath();
if(ext.endsWith(".mp3")) { // For mp3
status = true;
mp3_player = new MP3Player(selectedFile);
lblPlayURL.setText(selectedFile.getName());
}
else if(ext.endsWith(".wav")) {
status = false; //For .Wav
try {
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
clip = clip;
stream = AudioSystem.getAudioInputStream(selectedFile);
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
lblPlayURL.setText(selectedFile.getName());
}
catch(Exception e) {
//whatevers
}
}
}
}
}
To make the story shorter so what I have done is I have a variable that is set boolean to false. so whenever False is running it takes the Wav. when True its mp3. but as I said. the problem is sitting when.
Choose a song
Press play for the song
Choose new song
Press play for the new song (and here is where the 1st one song still going on which I don't want to)
Have I done something wrong with booleans?
EDIT: Forgot to add the open button:
btnOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnOpen) {
try {
Choose();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
}
edit : Stop method
,
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btnStop) {
if(!status) {
clip.stop();
lblPlaying.setText("Nothing plays right now!");
} else if(status == true) {
mp3_player.stop();
lblPlaying.setText("Nothing plays right now!");
}
}
}
});
You need to have another flag which tells you if it's playing or not. Then before you start the song, check the flag, then STOP any music if it's true, then start the new one.
You essentially have a design flaw. The system is capable of playing multiple songs at once, it didn't know you wanted to stop one of them.

Java JNA- Jar application hangs in 32 bit windows system

Here's a screenshot application. Compiled with 1.8 JDK, works perfectly well in 64 bit systems, but lags and hangs in two iterations in 32 bit systems.
Basically this application takes a screenshot using robot class, takes the file name from user which is a URL. Truncates and removes all illegal characters from it and saves it using a save as dialog box with time-stamp as the prefix.
I am using Windows Low Level KeyHook to initiate the screenshot with PrtSc key.
Error in 32 bit systems:
It only takes 2 screenshots and then does not respond when I press PrtSc for the 3rd time. Can JFrame cause any problems, it certainly loads up slow. Should I use any alternate text box than JFrame or is it because I have complied in java 1.8 jdk 64 bit environment, which wont work in lower versions of jdk or 32 bit systems.
public class KeyHook {
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
static JFileChooser fileChooser = new JFileChooser();
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
if (nCode >= 0) {
switch(wParam.intValue()) {
case WinUser.WM_KEYUP:
case WinUser.WM_KEYDOWN:
case WinUser.WM_SYSKEYUP:
case WinUser.WM_SYSKEYDOWN:
if (info.vkCode == 44) {
try {
Robot robot = new Robot();
// Capture the screen shot of the area of the screen defined by the rectangle
BufferedImage bi=robot.createScreenCapture(new Rectangle(0,25,1366,744));
JFrame frame = new JFrame();
JFrame.setDefaultLookAndFeelDecorated(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// prompt the user to enter their name
String name = JOptionPane.showInputDialog(frame, "Enter file name");
// frame.pack();
frame.dispose();
String fileName= dovalidateFile(name);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG", ".png");
fileChooser.setFileFilter(filter);
fileChooser.setSelectedFile(new File (fileName));
int returnVal = fileChooser.showSaveDialog(null);
if ( returnVal == JFileChooser.APPROVE_OPTION ){
File file = fileChooser.getSelectedFile();
file = validateFile(file);
System.out.println(file);
ImageIO.write(bi, "png", file);
}
}
catch (NullPointerException e1)
{e1.printStackTrace(); }
catch (AWTException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
private File validateFile(File file) {
DateFormat dateFormat = new SimpleDateFormat("HH.mm.ss.ddMMMMMyyyy");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
// System.out.println(dateFormat.format(cal.getTime()));
String filePath = file.getAbsolutePath();
if (filePath.indexOf(".png") == -1) {
filePath += "." + dateFormat.format(cal.getTime()) + ".png";
}
//System.out.println("File Path :" + filePath);
file = new File(filePath);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private String dovalidateFile(String name) {
String input = name.replace("https://www.","");
input = input.replaceAll("http://www.","");
input = input.replaceAll("https://","");
input = input.replace("http://","");
input = input.replace("/?",".");
input = input.replace("/",".");
input = input.replace("|",".") ;
input = input.replace("%",".");
input = input.replace("<",".");
input = input.replace(">",".");
input = input.replaceAll("\\?",".");
input = input.replaceAll("\\*",".");
input = input.replace(":",".");
input = input.replace("\\",".");
input = Character.toUpperCase(input.charAt(0)) + input.substring(1);
return input;
}
};
hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
if(!SystemTray.isSupported()){
return ;
}
SystemTray systemTray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage(KeyHook.class.getResource("/images/icon.png"));
//popupmenu
PopupMenu trayPopupMenu = new PopupMenu();
MenuItem close = new MenuItem("Exit");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
});
trayPopupMenu.add(close);
//setting tray icon
TrayIcon trayIcon = new TrayIcon(image, "captur", trayPopupMenu);
//adjust to default size as per system recommendation
trayIcon.setImageAutoSize(true);
try{
systemTray.add(trayIcon);
}catch(AWTException awtException){
awtException.printStackTrace();
}
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
System.err.println("error in get message");
break;
}
else {
System.err.println("got message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
lib.UnhookWindowsHookEx(hhk);
}
}
I don't have any experience with JNA, but there are several things that are wrong about your code - I don't think I got them all, but here are some:
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
quit=true;
}
});
The quit=true will never be reached because your program exit()s before it ever goes there.
2.
new Thread() {
public void run() {
while (!quit) {
try { Thread.sleep(10); } catch(Exception e) { }
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
doesn't make any sense since quit will never be true. Also spinning on a variable to detect a change will severly slow down your application (espacially with sleep-times of 10 ms). Why not do the unhook in your ActionListener?
3.
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
Here I'm not too sure because I don't have experience with JNA and the windows event system. The method waits for messages sent to the specified window, but since you don't specify any (second parameter is null) I don't think you will ever get one.
For each callback you are creating a new JFrame but at the end of the method you are only hiding it using frame.setVisible(false);. Since it is still referenced from various Swing-classes it will never be garbage-collected. This creates a memory-leak which will slow down your application. You will have to call frame.dispose() to get rid of it.

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";
}
}

Categories