In java the JFileDialog box will not appear multiple times - java

On my computer this block of code will only show the JFileChooser once instead of multiple times. (Im on a Mac)
I need to be able to show the dialog multiple times.
public class FileManager {
public static void main(String args[]) {
showDirectoryDialog();
System.out.println("BLOCKING");
showDirectoryDialog();
System.out.println("BLOCKING");
}
public static File showDirectoryDialog() {
System.out.println("Creating dialog");
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(null);
System.out.println("Dialog done");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
return f;
}
return null;
}
}
EDIT:
This does work if I create a static instance of JFileChooser and persist it.
does anyone know why this behaviour exists?
EDIT2:
I am using OSX 10.9.4
And I checked to make sure the second dialog box was not at the behind any other programs.
(unless they hid it behind the desktop lol)

Related

Why can't I pass my 'file' variable to actionPerformed?

I am trying to write a Java GUI that takes a file containing song information, allows the user to edit it, then outputs the new file with the same name. The file pathway is supplied by a run-time parameter, so the user would run the program like:
java myProgram myFile
This is how I am initializing the file in the main method (I am assuming since the file pathway is input as a run-time parameter, it must be assigned to a variable in the main method. I am not sure if I am correct):
public class SongDatabase extends JFrame
{
public SongDatabase(File file) throws IOException
{
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new Panel(file);
this.add(panel);
}
public static void main (String [] args) throws IOException
{
File file = null;
if (args.length == 1)
{
file = new File(args[0]);
}
else
{
System.out.print("No source file entered. Create source file (1 for yes 2 for no)?");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice ==2)
{
System.exit(0);
}
else
{
file.createNewFile();
}
}
JFrame frame = new SongDatabase(file);
frame.setVisible(true);
}
}
Upon selecting an "exit" button in the GUI, the program should take the stored data and output it using the same file pathway (basically overwriting the old file). Whatever I try, I can't seem to pass 'file' to the actionPerformed method, where this should be taking place. Based on responses from other questions about passing arguments to the actionPerformed this is what I tried in an attempt to get this to work:
public class Panel extends JPanel implements ActionListener{
...
File myFile;
public Panel(File file) throws IOException {
myFile = file;
...
}
public void actionPerformed(ActionEvent e) {
...
if (source == exitButton) {
try (PrintWriter outFile = new PrintWriter(myFile))
{
for (int i = 0; i < songBox.getItemCount(); i++)
{
Song songOut = songList.get(i);
outFile.println(songOut.getSongName()+ "\t" + songOut.getSongCode()+ "\t" + songOut.getSongArtist()+ "\t"+ songOut.getSongAlbum()+ "\t" + songOut.getSongPrice());
}
}
System.exit(0);
}
}
but that doesn't seem to work. For whatever reason, I get a FileNotFoundException. Are there any better alternatives to passing 'file' to actionPerformed?
Edit: I know it's not the path name or file that is the problem because when the offending code is removed the program imports the file correctly and runs as expected. When debugging the code, myFile does have the correct path so I would think that it should work fine, but it doesn't.

Simple way to choose a file

Is there some simple way to choose a file path in Java? I've been searching around, and JFileChooser keeps coming up, but that's already too excessive for what I want now, as it seems to require making a whole GUI just for that. I'll do it if need be, but is there a simpler way to get the file path?
I'm wondering if there's something like a JOptionPane dialog box to search for the file path.
When you have no surrounding UI, you can simply use this (based on the Answer from Valentin Montmirail)
public static void main( String[] args ) throws Exception
{
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog( null );
switch ( returnValue )
{
case JFileChooser.APPROVE_OPTION:
System.out.println( "chosen file: " + fileChooser.getSelectedFile() );
break;
case JFileChooser.CANCEL_OPTION:
System.out.println( "canceled" );
default:
break;
}
}
Here is the simpliest way to choose a file path in Java :
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(YourClass.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline);
} else {
log.append("Open command cancelled by user." + newline);
}
} ...
}
You can plug this actionPerformed to a button for example, and that's it. Your button will open a GUI to select a file, and if the user select the file JFileChooser.APPROVE_OPTION, then you can perform the action that you want (here only logging what was opened)
See the oracle documentation (https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html) if you want to do something else (not binding a button ?) or something more complex (filter for some extensions only ? ...)
JFileChooser is not that complicated if you only need to choose a file.
public class TestFileChooser extends JFrame {
public void showFileChooser() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}
}
public static void main(String args[]) {
new TestFileChooser().showFileChooser();
}
}

Browse button to select directory

I want to create a browse button in my web page to select directory and not file. I know that input type file won't work here but is there any way to do it with Javascript. I want to get the filepath of client machine which is possible in IE but other browser are not supporting but that is fine for me.
The way I got stuck is how to get file directory in button.
Below is the code I am using to call applet from browser but I am getting Detected from bootclasspath: C:\PROGRA~1\Java\jre7\lib\deploy.jar error in browser. I have compiled class file using Java 1.5
<applet code="com.life.draw.BrowsePage.class"></applet>
Code
public class BrowsePage extends JApplet {
#Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Browse the folder to process");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "+ chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "+ chooser.getSelectedFile());
} else {
System.out.println("No Selection ");
}
}
}
Why the hell are you calling this in the your paint method? This is likely trying creating to create new windows EVERY TIME the applet is painted.
public void paint(Graphics g) {
// TODO Auto-generated method stub
JFileChooser chooser = new JFileChooser();
/*...*/
Instead, create a JButton in your init method and attach an ActionListener to it...
public void init() {
setLayout(new GridBagLayout());
JButton browse = new JButton("...");
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Browse the folder to process");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "+ chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "+ chooser.getSelectedFile());
} else {
System.out.println("No Selection ");
}
}
});
add(browse);
}
You might also like to take a look at What Applets Can and Cannot Do
The only way you can get a local browse dialogue in a web browser is either by using <input type="file"/>, or by using a Java Applet or Adobe Flash plugin. There is no built in way to get a directory reference from JS in a web browser.
Also, you cannot read the contents of a client's hard disk, or even initiate a browse dialogue via JavaScript. If you were able to, it would impose considerable security issues.
In reference to reading a directory, take a look at the following posts:
Local file access with javascript
Getting content of a local file without uploading
Javascript: Getting the contents of a local server-side file
By the sound of it, you're going to need to write a flash plugin that lets you select a directory locally. Your users will be given a security warning when downloading the plugin, though.
Edit:
There's also the webkit based method, but this will only work in webkit based browsers (Chrome, Safari etc).
How do I use Google Chrome 11's Upload Folder feature in my own code?

JFileChooser not showing up

I have a method that takes a txt file as an input. I used to use string by typing the direct path to the file.
But it became burdensome whenever I tried to use different file for an input. I try implementing JFileChooser but with no luck.
This is the code, but nothing happening.
public static JFileChooser choose;
File directory = new File("B:\\");
choose = new JFileChooser(directory);
choose.setVisible(true);
File openFile = choose.getSelectedFile();
FileReader fR = new FileReader(openFile);
BufferedReader br = new BufferedReader(fR);
As per Java tutorial on How to Use File Choosers:
Bringing up a standard open dialog requires only two lines of code:
//Create a file chooser
final JFileChooser fc = new JFileChooser();
...
//In response to a button click:
int returnVal = fc.showOpenDialog(aComponent);
The argument to the showOpenDialog method specifies the parent
component for the dialog. The parent component affects the position of
the dialog and the frame that the dialog depends on.
Note as per docs it can also be:
int returnVal = fc.showOpenDialog(null);
If the parent is null, then the dialog depends on no visible window,
and it's placed in a look-and-feel-dependent position such as the
center of the screen.
 
Also have a read on Concurrency in Swing if you haven't already.
No blocking code (as David Kroukamp suggest). It solves "not showing up" problem.
Runnable r = new Runnable() {
#Override
public void run() {
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if( jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ){
selected = jfc.getSelectedFile();
}
}
}
SwingUtilities.invokeLater(r);
I personally found that the first dialog would show, but subsequent dialogs wouldn't show. I fixed it by reusing the same JFileChooser with this code.
JFileChooser jfc = new JFileChooser();
File jar = selectFile(jfc, "Select jar to append to");
File append = selectFile(jfc, "Select file to append");
//When done, remove the window
jfc.setVisible(false);
public static File selectFile(JFileChooser jfc, String msg) {
if (!jfc.isVisible()) {
jfc.setVisible(true);
jfc.requestFocus();
}
int returncode = jfc.showDialog(null, msg);
if (returncode == JFileChooser.APPROVE_OPTION) return jfc.getSelectedFile();
return null;
}
For JFileChoosers, you're supposed to call objectName.showOpenDialog(Component parent) or objectName.showOpenDialog(Component parent). These methods will return an integer, which you can use to compare to the static constants set in JFileChooser to determine whether the user clicked cancel or open/save. You then use getSelectedFile() to retrieve the file that the user has selected.
Ex (There might be small errors):
class Example {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser();
File selected;
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selected = jfc.getSelectedFile();
}
}
}
The Java API is a great resource for figuring out what objects can do what, and how. Here's the page for JFileChoosers
The API pages are usually found when you Google the object name. They're usually the first ones that come up as a result as well.

java form button order execution

i write a method to create a form(3 buttons and a textBox), then i call it in main.
but when i run program, before i enter information in the form (method form6 ),
Other commands that are executed! "s4 and ontname chenged in the form".
this is a part of my code:::::::::::
//////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
System.out.println("*begin main*"); // call form method
String s4= form6(); // s4 is returned by method.
System.out.println("s3333*"+s4);
System.out.println("ont:"+ontname);//it's global }
//////////////////////////////////////////////////////////////////////////
i have 2 questions:::
1--- While the form is running, other commands are executed!
What is their order execution?
2. --- i want to define a button to when i click it,it closes the form.
thanks all.
If I get your code correctly, ontname is either (1) a class member (declared outside a method) or (2) a local variable, which is declared in the method that contains this code snippet.
In both cases there is no need to "return" ontname just because it is not declared inside the anonymous ActionListener instance.
The following example illustrates a typical pattern for this problem:
public void someMethod() {
// ...
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
fc.showOpenDialog(null);
File selFile = fc.getSelectedFile();
setOntName(selFile.getPath()); // <-- here we call another method
}
});
// ...
}
void setOntName(String ontName) {
// do something with ontName
}
Alternativly: declare ontName as a static class member (only):
private static String ontName = ""; // <-- accessible from main method
public static void main(String[] args) {
// ...
}
// more methods.
You can't return a value in this Method because the ActionListenerInterface does not allow this. But you can call another method from within the actionPerformed() method and pass the ontname to it.
You can also close the third button in the new method. Or define the third button as final and use it in the actionPerformed() method.
E.g.
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
fc.showOpenDialog(null);
File selFile = fc.getSelectedFile();
ontname=selFile.getPath();
System.out.println("filepath: "+ontname); //it works correctly.
anotherMethod(ontname);
}
});
private void anotherMethod(String path) {
//doSomething with the path
//close third button here
}
You could probably define your variable ontname as global, outside of your function:
var ontname = null;
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// ...
ontname=selFile.getPath();
}
});
// ...
System.out.println("filepath: "+ontname);
If you want to remember the values, then they should be class level variables.
But, generally, you would want to pass these to some other method to do some processing on them (or, say, persist them in a file). You can pass these as parameters to the other method.
(The second one is better in most cases, I don't know much about your app, so I am unable to give one answer)
There are other problems with your code:
You need to check whether the use has clicked the "Ok" or "Cancel" button in the open dialog to decide whether to get the file or not.
String filename = File.separator+"c:"; does not really make sense. Perhaps you meant String filename = "c:"+File.separator; But even this is not very useful. File.separator is for getting the platform specific file separator char (\ in Windows, / on linux) but since you are hard coding c:, you are anyway constrainting your app to Windows. You might want to have a better platform independent way (start at the "default" path, new JFileChooser() without arguments, and then remember the path the user last used, and proceed from there)
If the argument to the showOpenDialog method is your parent frame, then the dialog would be centered on the parent frame, and would, in most cases, look nicer.
You might also want to relook your variable names.
button2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
int option = fc.showOpenDialog(null);
if(option = JFileChooser.APROVE_OPTION)
{
File selFile = fc.getSelectedFile();
String ontname=selFile.getPath();
System.out.println("filepath: "+ontname); //it works correctly.
doSomeOperation(ontname); //Or, declare ontname as a class level variable.
}
}
});

Categories

Resources