JFileChooser not showing up - java

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.

Related

How to open a generated PDF in vaadin?

In my vaadin application I have a Table with an additional column containing a print Button. The Button calls the following util method to create a pdf and open it in a new window (ui parameter is the button):
public static void printPDF(Offer offer, AbstractComponent ui) throws IOException, DocumentException, TemplateException {
// ... create PDF
FileResource resource = new FileResource(pdfFile);
BrowserWindowOpener opener = new BrowserWindowOpener(resource);
opener.setFeatures("");
opener.extend(ui);
}
Now clicking the button the first time does not work. Clicking it the second time works. Clicking it the third time, opens two windows. This increases on every further click.
I also want to open the pdf using the context menu e.g.
table.addActionHandler(new Handler()...
There I don't even have a button to extend. I would prefer to, not use the .extend() part and just open a new window. How can I do that?
EDIT: This blocks the button from opening mulitple instances, still not a nice solution and the first click does not work.
Collection<Extension> extensions = ui.getExtensions();
for (Extension e : extensions) {
if (e instanceof BrowserWindowOpener) {
((BrowserWindowOpener) e).setResource(resource);
return;
}
}
I guess I would need to create a BrowserWindowOpener for every print Button in my Table.
Not a very clean solution, the table may contain lots of rows which would create a lot of BrowserWindowOpener instances which will never be used. The context menu problem would not be solved as well.
EDIT2: This is the other solution I tried:
ResourceReference rr = ResourceReference.create(resource, ui, "print");
Page.getCurrent().open(rr.getURL(), "blank_");
Here I get the following error:
Button (175) did not handle connector request for
print/2016_9090_R_1634500091131558445.pdf
You can use the FileDownloader to achieve what you want.
FileResource resource = new FileResource(pdfFile);
FileDownloader downloader = new FileDownloader(resource);
Button pdf= new Button("Download PDF");
downloader.extend(pdf);
Use this code
Window window = new Window();
((VerticalLayout) window.getContent()).setSizeFull();
window.setResizable(true);
window.setCaption("Exemplo PDF");
window.setWidth("800");
window.setHeight("600");
window.center();
StreamSource s = new StreamResource.StreamSource() {
#Override
public InputStream getStream() {
try {
File f = new File("C:/themes/repy.pdf");
FileInputStream fis = new FileInputStream(f);
return fis;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
};
StreamResource r = new StreamResource(s, "repy.pdf", mainLayout.getApplication());
Embedded e = new Embedded();
e.setSizeFull();
e.setType(Embedded.TYPE_BROWSER);
r.setMIMEType("application/pdf");
e.setSource(r);
window.addComponent(e);
getMainWindow().addWindow(window);

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();
}
}

How to pass a file location as a parameter as a string?

Currently I pass a hardcoded string file location to my object method which uses the string in the .getResources() method to load an image file. I am now trying to chooses an image using a load button and pass the loaded file location as a string into the getResource() method. I am using the filename.getAbsolutePath() method to retrieve the file location then passing the filename variable into the object method however this provides me with the following error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
The line of code that it points to having the error is the .getResources line where the image is loaded. I will post the code below to better understand my problem.
btnLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File loadImage = fc.getSelectedFile();
String filename = loadImage.getAbsolutePath();
filename = filename.replaceAll("\\\\", "\\\\\\\\");
picLocation = filename;
ImageSwing imageSwing = new ImageSwing(filename);
System.out.println(filename);
}
}
The output of the file name is correct yet it still wont pass into the object.
public class ImageSwing extends JFrame
{
public JLabel label;
public ImageSwing(String S){
super("Card Stunt"); //Window Title
setLayout(new FlowLayout()); //lookup grid layout
Icon flag = new ImageIcon(getClass().getResource(S));
label = new JLabel(flag);
label.setToolTipText(S);
setSize(1350, 800);
//setMinimumSize(new Dimension(1200, 760));
}//main
}
It seems like you create an absolute filename with loadImage.getAbsolutePath(), but then you try to use this as a class path resource with new ImageIcon(getClass().getResource(S)).
Instead, you should just pass the absolute filename, as a string, to ImageIcon:
Icon flag = new ImageIcon(S);
Also, don't forget to add the label to the frame...
getContentPane().add(label);
Also, I'm not on Windows right now, but I don't think filename.replaceAll("\\\\", "\\\\\\\\"); is necessary.

In java the JFileDialog box will not appear multiple times

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)

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?

Categories

Resources