Browse button to select directory - java

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?

Related

JfileChooser does not close the window after entering a non-existent file

Sorry for my English. I have to write notepad in javafx. I open new File use FileChooser. And if user type wrong name of file my program have to show communication and extort type correct name file. But when I choose open button filechooser's window disappear. I want that filechooser window not disappear but user can type correct name file again.
public void onActionOpenFile() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Otwórz plik");
File file = fileChooser.showOpenDialog(new Stage());
try {
if (file.exists()) {
ReadFile read = new ReadFile(file.getAbsoluteFile().toPath());
read.readFile();
} else {
}
}catch (NullPointerException e){
e.getMessage();
}
}
I want that my program work as notepad in windows when I open showOpen dialog and I type wrong name file.

dynamically adding hyperlinks to rtf file in JEditorPane

I am currently building a word processor for use in a multi-window media annotation tool, written in Java. It is for film students to write essays and embed them with links to multimedia clips.
I want the user to be able to highlight text in an rtf document and create a link to a media file in the project. When clicked the link will display the media in its associated window.
I would like to know if it is possible to dynamically create hyperlinks in rtf documents in Java? As is possible in Word, for example.
At the moment I am using a JEditorPane with the Advanced RTF Editor Kit (http://java-sl.com/advanced_rtf_editor_kit.html). I am struggling to find any sort of a solution.
Any help or pointers greatly appreciated.
Thanks
Edit:
code, with parts 1 & 3 from # Eric's answer added
`item3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
//use FX thread to open FileChooser
Platform.runLater(new Runnable() {
#Override
public void run() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("create link");
String startDirectory = System.getProperty("user.home") + File.separator + "Pictures";
fileChooser.setInitialDirectory(new File(startDirectory));
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("JPEG files (*.jpg)", "*.jpg");
FileChooser.ExtensionFilter extFilter2 = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.png");
FileChooser.ExtensionFilter extFilter3 = new FileChooser.ExtensionFilter("JPG files (*.jpeg)", "*.jpeg");
fileChooser.getExtensionFilters().addAll(extFilter,extFilter2, extFilter3);
File imageFile = fileChooser.showOpenDialog(stage);
if(imageFile != null){
Image image = ImageViewerController.getImage();
try {
image = new Image(imageFile.toURI().toURL().toExternalForm().toString());
int start = textArea.getSelectionStart();
int end = textArea.getSelectionEnd();
textArea.getDocument().remove(start, end);
String newString = "{\field{\*\fldinst HYPERLINK 'http://www.google.com/'}{\fldrslt http://www.google.com}}";
textArea.getDocument().insertString(start, newString , null);
textArea.addHyperlinkListener(new HyperlinkListener() {
#Override
public void hyperlinkUpdate(HyperlinkEvent hle) {
if (HyperlinkEvent.EventType.ACTIVATED.equals(hle.getEventType())) {
System.out.println(hle.getURL());
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(hle.getURL().toURI());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});`
I think there are various parts in your question:
1. Replace selected text in a Document:
Get the selected range with:
int start = editorpane.getSelectionStart();
int end = editorpane.getSelectionEnd();
Replace the text with:
editorpane.getDocument().remove(start,end);
editorpane.getDocument().insertString(start, newString, null);
Note: replace null with actual attribute set if needed.
2. Create a RTF-formatted hyperlink. I think this post has everything.
3. React to hyperlink clicks: As explained in the docs, you must add a HyperlinkListener to the editor pane to open the corresponding media. However a condition for this to work is that the editor kit generates HyperlinkEvents when hyperlinks are clicked. This is definitely the case for HTML documents, but since you are using a 3rd party library, I cannot confirm it will work the same way...

display text in jtextfield takes too long

I would really appreciate your help;
I'm using java (netbeans ide), i'm working with filechooser, when i choose a directory, i need to display it's path on a jtextfield. However nothing appears until the program is over (untill all the files of the directory are parsed and treated), I would like it to appear as soon as the program starts.
Please help me out, here is my code:
JFileChooser fch = new JFileChooser("C:\\");
fch.addChoosableFileFilter(filter);
fch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int ret = fch.showOpenDialog(null);
int apr=0;
if (ret==JFileChooser.APPROVE_OPTION)
{
apr=1;
jTextField1.setText(fch.getSelectedFile().toString());
}
else jTextField1.setText("Nothing clicked!!!");
.......... the rest of the code .........
when I don't click the msg appears, yet when i do, the path won't apprear till after the program is finished
The code of JFileChooser... probably resides in an ActionListener. This is handled on the sole event handling thread. So do an invokeLater.
#Override
public void actionPerformed(ActionEvent event) {
...
EventQueue.invokeLater(new Runnable() { // Added
... rest of the code
}); // Added
}
Here I think "rest of the code" might be causing the delay, but you might try differently.

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)

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.

Categories

Resources