So I have been trying to make a filechooser that opens a text file and then paste the contents in a JtextArea I have defined as textArea.
But I cannot get my showOpenDialog to not give an error while having the argument (this), and I researched and the answer was to fill in (null) and this does make the filechooser work but when I try to print the contents of it it also just returns null. I am using the Eclipse program hence the auto filled code.
I am fairly new to Java and have no clue what is going wrong.
Im really sorry if this is not the way to post things here.
JButton btnNewButton = new JButton("Bladeren");
btnNewButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
String content = readFile(selectedFile, StandardCharsets.UTF_8);
System.out.println(content);
textArea.setText(content);
}
}
private String readFile(File selectedFile, Charset utf8) {
// TODO Auto-generated method stub
return null;
}
}
);
You can look into the API that the parameter has to be from type Component. So what does this mean in your example? Which other class/interface does your class extends from or implements?
You didn't paste the code of your readFile method but ask why it returns null? This way we cannot help you so please post the code.
Related
I am trying to build a project where I will be exporting the data from h2db and store it as CSV file.
I am planning on taking the destination path for the CSV file(which is to be saved) from the user.
Class name is Export and here in default constructor swing events are happening.
I want the value of getSelectedFile(),(that is the path selected by user) to be able to use in another method.
I have created class variable - path of string type when trying to use the value all I am getting is null.
Thanks in Advance :)
Here is the code,
public class export extends JFrame{
private BufferedWriter fileWriter;
private JPanel contentPane;
private static JTextField tableName;
private JButton exportButton;
private JButton PathButton;
private String path;
private String temp;
public export() {
//Some labels and textfields
JFrame frame = new JFrame("CSV Export");
PathButton = new JButton("Destination Path");
PathButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int option = fileChooser.showOpenDialog(frame);
if(option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
path = fileChooser.getSelectedFile().toString();
label.setText("Folder Selected: " + file.getName());
System.out.println(file.getName());
System.out.println("getCurrentDirectory(): "
+ fileChooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "
+ fileChooser.getSelectedFile());
path = fileChooser.getSelectedFile().toString();
exportButton.setEnabled(true);
}else {
label.setText("Open Command canceled");
exportButton.setEnabled(false);
}
}
});
PathButton.setFont(new Font("Tahoma",Font.PLAIN,13));
PathButton.setBounds(120,230,130,30);
contentPane.add(PathButton);
}
}
In application im asking user to choose folder however using code below Im unable to use this input as variable path
public class csvtoxls {
public static void main() throws IOException {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setDialogTitle("Wybierz folder do konwersji: ");
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setAcceptAllFileFilterUsed(false);
int returnValue = jfc.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
if (jfc.getSelectedFile().isDirectory()) {
System.out.println("You selected the directory: " + jfc.getSelectedFile());
So in order to achieve this I used function:
public class getpath {
public static String pickPath(JFileChooser fileChooser)
{
String path = null;
/* create a JFrame to be the parent of the file
* chooser open dialog if you don't do this then
* you may not see the dialog.
*/
JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);
// get the return value from choosing a file
int returnVal = fileChooser.showOpenDialog(frame);
// if the return value says the user picked a file
if (returnVal == JFileChooser.APPROVE_OPTION)
path = fileChooser.getSelectedFile().getPath();
return path;
}
}
Variable:
Path workDir = Paths.get(getpath.pickPath(jfc));
The problem with this solution is that user have to choose folder twice wich can easily lead to mistake. Is there way to get this path easier?
I found here: what I was searching for but still I have some issues.
This is my action code:
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) throws IOException {
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile());
jEditorPane1.setText(image);
}
}
Here is a screenshot of what happens, as you can see the image is not loaded.
http://postimg.org/image/agc665ih1/
But if I save the file (with save button) and reopen the same file (with open button), the image is there and is perfectly loaded.
I already tried the .repaint() and .revalidate() methods, but is not working..
Any idea?
This may be problem in setting up path in JEditorPane page. use this:
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile().getPath());
I am assuming that you have already selected appropriate editorKit for JEditorPane.
So now I can answer with my code. I am using this class for the file chooser:
import java.io.File;
import javax.swing.filechooser.FileFilter;
class jpgfilter extends FileFilter {
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".jpg");
}
public String getDescription() {
return "JPG image (*.jpg)";
}
}
And in my main class I have this:
FileChooser1 = new javax.swing.JFileChooser();
FileChooser1.setDialogTitle("Choose your image:");
FileChooser1.setFileFilter(new jpgfilter());
And that's it.
So I actually found some kind of a solution but I think there is really too much code and that I should do it easily..I actually insert the image and simultaneously save and open the content of the EditorPane as .html file.
The code:
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1
.getSelectedFile().getPath());
jEditorPane1.setText(image);
String type = jEditorPane1.getContentType();
OutputStream os = new BufferedOutputStream(new FileOutputStream(
"/Library/java_test/temp" + ".html"));
Document doc = jEditorPane1.getDocument();
int length = doc.getLength();
if (type.endsWith("/rtf")) {
// Saving RTF - use the OutputStream
try {
jEditorPane1.getEditorKit().write(os, doc, 0, length);
os.close();
} catch (BadLocationException ex) {
}
} else {
// Not RTF - use a Writer.
Writer w = new OutputStreamWriter(os);
jEditorPane1.write(w);
w.close();
}
String url = "file:///" + "/Library/java_test/temp" + ".html";
jEditorPane1.setPage(url);
}
As the title states, is there a way to select multiple directories at once (all sub-directories immediately within a primary directory) with JFileChooser so I don't have to re-open the file chooser window for each directory?
Once again I've solved my own question after asking it.
The thing that was preventing me from getting it to work previously was I was using the check for multi-select rather than the set for multi-select, and apparently was using that wrong as well as I kept getting an error. Anyway, the working version is below:
class AddDirectory implements ActionListener {
public void actionPerformed(ActionEvent ae) {
File[] theDir = null;
theDir = selectDir();
if(theDir != null) {
for(File z : theDir) {
String[] curRow = { z.toString(), "Waiting"};
dlm.addRow(curRow);
}
}
return;
}
private File[] selectDir() {
JFileChooser fileChooser = new JFileChooser(lastDir);
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int showOpenDialog = fileChooser.showOpenDialog(null);
if (showOpenDialog != JFileChooser.APPROVE_OPTION) {
return null;
}
File[] uploadDir = fileChooser.getSelectedFiles();
lastDir = new File(uploadDir[uploadDir.length-1].getParent());
return uploadDir;
}
}
Once I get the directories, they're loaded into a JTable to be modified before running the rest of my code on them.
in my main class I have this method
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TxtFileFilter());
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File f = fileChooser.getSelectedFile();
}
}
I want to pass the selected file into the argument of an object in another class of the same project and package:
public class ImportFile {
File fileToImport = new File("C:/data/myData.txt");//path will be set from GUI
How to do this? Thanks!
You can do someting like this:
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TxtFileFilter());
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File f = fileChooser.getSelectedFile();
SomeClass c = new SomeClass(f);
c.processFile();
}
}
Although it would be better to do the processing in another thread instead of the Event dispatch thread.
In your main class you should return the file F.
That way from any other class in the same package you can call the OpenActionPerformed() method and have it returned into a new File object in whatever class you use it from.