How to implement a SaveAs Dialog in a JfreeChart SaveAsPNG method - java

Please, I need your help. Could you tell me how to implement a SWT SaveAs Dialog in the next code? I need that user can choose where he wants to save the chart. Thanks!
try {
File file = new File("mychart.png");
float calidad = 1;
ChartUtilities.saveChartAsJPEG(file, calidad, chart, 800, 600);
MessageDialog.openInformation(shell, "Save Chart", "The file has been saved");
} catch (IOException e1) {
e1.printStackTrace();
MessageDialog.openInformation(shell, "Save Chart", "Error saving file. Please try again...");
}

Use the SWT FileDialog - something like:
Shell shell = ... current shell
FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
fileDialog.setFilterExtensions(new String [] {"*.png", "*.*"});
fileDialog.setFilterPath(.... any default path you want ....);
String filePath = fileDialog.open();
// TODO check for null 'filePath' - user canceled the save
File file = new File(filePath);
ChartUtilities.saveChartAsPNG(file, calidad, chart, 800, 600);

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:

Can't load Image into JTextArea using Swing

I am using JFileChooser to load image from the desktop into JTextArea but when I load image from PC, the software hangs.
Here is the code of OpenActionPerformed method of the file chooser.
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == fileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
// What to do with the file, e.g. display it in a TextArea
textarea.read( new FileReader( file.getAbsolutePath() ), null );
} catch (IOException ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
A JTextArea is for text not for images.
If you want to display an image then add an ImageIcon to a JLabel and add the label to the JFrame.
Read the section from the Swing tutorial on How to Use Icons for more information on reading images and displaying Icons.

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

how to properly save a picture path in a database and assign it into a button?

How can I know the path of the picture that will be store in this button. Also, what type of picture will you recommend me to upload in this button ?
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fc.getSelectedFile();
btnNewButton.setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
});
how can i know the path of the picture that will be store in this
button
This can be easily done by calling File.getPath() method:
File file = fc.getSelectedFile();
System.out.println(file.getPath());
Additionaly you can store this path in the button through JComponent.putClientProperty(Object key, Object value):
File file = fc.getSelectedFile();
btnNewButton.putClientProperty("imagepath", file.getPath());
what type of picture will you recommend me to upload in this button ?
It can be JPG, PNG, BMP, WBMP and GIF, as per javax.imageio package description. Be aware Java doesn't support ICO format natively: Adding image to JButton

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