Browse button not show file path in text box in java - java

I created a browse button and here is the code for that:
private void lookForExeClick () throws FileNotFoundException{
DirectoryDialog dlg = new DirectoryDialog(Display.getCurrent().getActiveShell());
String directoryPath = dlg.open();
//File file = new File(directoryPath, "MyFileName.txt");
//FileOutputStream outputStream = new FileOutputStream(file);
My text box that I created on the gui is this:
exeLocationText = new Text(controlGroupForSingleRun, SWT.BORDER);
exeLocationText.setText("");
data = new GridData();
data.widthHint = 265;
exeLocationText.setLayoutData(data);
How do I get the filepath that I choose in the directory dialog box after I click browse into the text box that I created in java. Any advice would be helpful. Thanks.

In your click handler, you would just have:
String directoryPath = dlg.open();
if(directoryPath != null)
exeLocationText.setText(directoryPath);

Related

JavaFX: FileChooser is blinking

It first appears in the left upper corner of the screen and then shows in the middle of the screen.
It is code:
private static File fileChooserDialog( final String initialDirectory, final String initialFileName, final boolean open,
final String filterString, final String... extensions) {
FileChooser fileChooser = new FileChooser();
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(filterString, extensions);
fileChooser.getExtensionFilters().add(extFilter);
Stage stage = new Stage();
File resultFile;
if(open) {
resultFile = fileChooser.showOpenDialog(stage);
} else {
resultFile = fileChooser.showSaveDialog(stage);
}
if(resultFile != null) {
lastSelectedFilePath = resultFile.getParent();
}
return resultFile;
}
You should not create a new Stage every time you want to show a FileChooser. Remove this line:
Stage stage = new Stage();
And use your application's Window as an owner for the FileChooser. For example, if you are trying to show this dialog when the user clicks a button, you can get the Window like this:
Button button = new Button("Browse");
button.setOnAction(event -> {
Window window = button.getScene().getWindow();
fileChooser.showOpenDialog(window);
event.consume();
});

java.lang.IllegalArgumentException: Invalid URL: unknown protocol: m / filechooser path problem [duplicate]

This question already has answers here:
How to load Image file to ImageView?
(3 answers)
Closed 3 years ago.
I am trying to add an image to a gridview using a button that opens up a filechooser that only accepts images. I am getting an exception error when im using the file path from the filechooser to create a setImage to my grid view. I think this is because the path im getting is just not right.
Here is the code where it fails:
public void makeBrowseButton(Stage primaryStage) {
//attach handler
browseButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser fileChooser = new FileChooser(); // create object
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")); //filter for music files
//FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
if ( !parentPath.equalsIgnoreCase("")) { //go to previous directory if exists
File parentPathFile = new File(parentPath);
fileChooser.setInitialDirectory(parentPathFile);
}
File selectedFile = fileChooser.showOpenDialog(primaryStage);
if (selectedFile != null) { // display the dialog box
String wholePath = selectedFile.getPath();
String name = selectedFile.getName();
String megaPath = selectedFile.getAbsolutePath();
parentPath = selectedFile.getParent();
System.out.println("wholePath: " + wholePath);
System.out.println("File Name: " + name);
System.out.println("megaPath: " + megaPath);
Image newAwesomeImage = new Image(megaPath);
ImageView view = new ImageView();
view.setImage(newAwesomeImage);
paneofgridmonkeys.add(view, 0, 0);
//paneofgridmonkeys.add(new Label("Changed the image!"), 0, 1);
createDisplay(primaryStage);
}}});
}
The error message is the title it is saying that the exact problem is line:
view.setImage(newAwesomeImage);
as for my system.out results this is what im getting:
wholePath: M:\Home\BenStillerDuckFace.jpg
File Name: BenStillerDuckFace.jpg
megaPath: M:\Home\BenStillerDuckFace.jpg
ive tried all of these and non work. Any ideas?
The Image(String url) constructor requires a URL string, not a file name. A file name is not a URL.
To convert a file name string to a URL string, do one of these:
// Java 7+
String megaUrl = Paths.get(megaPath).toUri().toURL().toString();
// Java 1.4+
String megaUrl = new File(megaPath).toURI().toURL().toString();

Eclipse plugin display text which is of any language

i am new to eclipse plugin development. i created a plugin which loads a unicode saved text file from the folder & displays it on a dialog & also setting it for the Label. If it is, in an English Language, everything is working fine. But if i try to load any other language text, it is displaying empty. How can i get through this.
Here is some code on how i am displaying it on dialog:
Shell shell = Display.getCurrent().getActiveShell();
// Loading the file by creating the assets folder & Temp.txt file inside
// Eclipse Plugin
URL url = FileLocator.find(bundle, new Path("assets/Temp.txt"), null);
URL fileUrl = null;
try {
fileUrl = FileLocator.toFileURL(url);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
File file = new File(fileUrl.getPath());
String Message = "";
try {
if (file.exists()) {
BufferedReader in = new BufferedReader(
new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
if (str.contains(LanguageSelected)) {
System.out.println(str);
Message = Message + "\n" + str;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Creating the dialog
Shell dialog = new Shell(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
...
// Adding Label to dialog
Label LabelMessage = new Label(dialog, SWT.LEFT);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 6;
// Adding Message to the dialog
LabelMessage.setLayoutData(data);
LabelMessage.setBackground(new Color(null, 255, 255, 255)); // White
LabelMessage.setText(Message);
In your launch configuration, make sure you are setting the -nl parameter to the language you want to display. See http://help.eclipse.org/indigo/topic/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html for information.

SWT Drag to Explorer (Windows) or Finder (OS X)

I've got an SWT application with a bunch of graphical elements. I'd like for the user to be able to drag an element to their Desktop / Windows Explorer / OS X Finder. When they drop the element, I need the path that they dropped it to, so that I can create a file in that location which represents the element.
I don't think I can use a FileTransfer, because there is no source file. There is a source object which can create a file, but only once it knows where to put it.
Inlined below is a simple example of what I'm trying to achieve, there is a text box with a label to drag from. If the user drags to some folder or file, I'd like to get the path that they dragged to. If they dragged to a file, I'd like to replace the contents of that file with whatever is in the text box. If they dragged to a folder, I'd like to create a file called "TestFile" with the contents of whatever is in the text box.
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class DesktopDragExample {
public static void main(String[] args) {
// put together the SWT main loop
final Display display = Display.getDefault();
display.syncExec(new Runnable() {
#Override
public void run() {
Shell shell = new Shell(display, SWT.SHELL_TRIM);
initializeGui(shell);
//open the shell
shell.open();
//run the event loop
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
});
}
// create the gui
private static void initializeGui(Composite parent) {
GridLayout layout = new GridLayout(2, false);
parent.setLayout(layout);
// make the instructions label
Label infoLbl = new Label(parent, SWT.WRAP);
GridData gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
gd.horizontalSpan = 2;
infoLbl.setLayoutData(gd);
infoLbl.setText(
"You should be able to drag to the desktop, Windows Explorer, or OS X Finder.\n" +
"If you drag to a file, it will replace the contents of that file with the contents of the text box.\n" +
"If you drag to a folder, it will create a file named 'TestFile' whose contents are whatever is in the text box.");
// make the text element
final Text text = new Text(parent, SWT.SINGLE | SWT.BORDER);
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
text.setLayoutData(gd);
// make the label element
Label label = new Label(parent, SWT.NONE);
label.setText("Drag me");
// listener for drags
DragSourceListener dragListener = new DragSourceListener() {
#Override
public void dragStart(DragSourceEvent e) {
e.detail = DND.DROP_COPY;
}
#Override
public void dragFinished(DragSourceEvent e) {
System.out.println("--dragFinished--");
System.out.println("e.data=" + e.data);
}
#Override
public void dragSetData(DragSourceEvent e) {
System.out.println("--dragSetData--");
System.out.println("e.data=" + e.data);
}
};
// the DragSource
DragSource dragSource = new DragSource(label, DND.DROP_COPY);
dragSource.setTransfer(new Transfer[]{FileTransfer.getInstance()});
dragSource.addDragListener(dragListener);
}
private static void draggedTo(String path, String textBoxContents) {
System.out.println("Dragged the contents '" + textBoxContents + "' to '" + path + "'");
}
}
Here are some other people with the same problem, but looks like no solution so far:
Drag from SWT to Desktop, ..want destination path as String
The only way to do it is by creating a temporary file and then using the FileTransfer. I suspect that's what you'd have to do in native code anyways. I'll see if I have enough time to sketch the sample...
You don't get the file location from and write the file yourself. Dragging to the Desktop implies a FileTransfer (you can check what type of transfer is supported in dragSetData).
This means that SWT expecting a String[] of file paths in DragSourceEvent.data. If you set this in the dragSetData method, then SWT copies those files to your drop target - e.g. the Desktop.
#Override
public void dragSetData(DragSourceEvent e) {
System.out.println("--dragSetData--");
System.out.println("Is supported: " + FileTransfer.getInstance().isSupportedType(e.dataType));
FileTransfer f = FileTransfer.getInstance();
String[] filePaths = {"C:\\CamelOut\\4.xml" } ;
e.data = filePaths;
}
};

Drop File on SWT Label with Image (DND)

Problem description:
The user should be able to drag an Image-File from his computer to a RCP Application. The drop-target is a SWT-Label which is generated through the Eclipse FormToolkit. (Eclipse Forms)
With the following code, the user is able to drag Image-Files as well as Images from a Browser and drop them on the label (works well).
The problem occurs, when the label shows a image:
lblImage.setImage()
In my example, I set the image of the label, after the user dropped a file. As a consequence, subsequent drags are no longer registered.
(dragEnter method is no longer invoked)
/** create label **/
Label lblImage = fFormToolkit.createLabel(fForm.getBody(), "");
GridData gd = new GridData();
gd.widthHint = 200;
gd.heightHint = 200;
lblImage.setLayoutData(gd);
/** drag drop support **/
int ops = DND.DROP_COPY | DND.DROP_LINK | DND.DROP_DEFAULT;
final FileTransfer fTransfer = FileTransfer.getInstance();
final ImageTransfer iTransfer = ImageTransfer.getInstance();
Transfer[] transfers = new Transfer[] { fTransfer, iTransfer };
DropTarget target = new DropTarget(fLblArtWork, ops);
target.setTransfer(transfers);
target.addDropListener(new DropTargetAdapter() {
#Override
public void drop(DropTargetEvent event) {
if (event.data instanceof String[]) {
String[] filenames = (String[]) event.data;
if (filenames.length > 0){
Image i = new Image(Display.getCurrent(), filepath);
lblImage.setImage(i);
}
} else if (event.data instanceof ImageData) {
Image i = new Image(Display.getCurrent(), data);
lblImage.setImage(i);
}
}
public void dragEnter(DropTargetEvent event) {
System.out.println("drag enter");
event.detail = DND.DROP_COPY;
}
});
Question: How do I register dragEnter Events on a SWT Label that shows an Image?
Thanks
In your example there were some problems that caused this not to compile for me. After I fixed the issues I was able to drag png files onto the component and each successive drop changed the image correctly.
Here are the changes:
Original
DropTarget target = new DropTarget(fLblArtWork, ops);
became:
DropTarget target = new DropTarget(lblImage, ops);
Original
Image i = new Image(Display.getCurrent(), filepath);
became:
Image i = new Image(Display.getCurrent(), filenames[0]);
Original
Image i = new Image(Display.getCurrent(), data);
became
Image i = new Image(Display.getCurrent(), (ImageData) event.data);
I also create my label the following way:
final Label lblImage = new Label(shell, SWT.NONE);
but that shouldn't make a difference.
I used SashForm here to set an background image from the local system. AS per your requirement I have done the text and label also but I didn't set. You can set it by the labelobject.setImage(image);
final SashForm sashForm = new SashForm(composite, SWT.BORDER);
sashForm.setBounds(136, 10, 413, 237);
final Label lblHello = new Label(composite, SWT.NONE);
DragSource dragSource = new DragSource(lblHello, DND.DROP_NONE);
ImageTransfer imgTrans=ImageTransfer.getInstance();
FileTransfer fileTrans=FileTransfer.getInstance();
Transfer[] transfer=new Transfer[] { fileTrans,imgTrans,TextTransfer.getInstance() };
DropTarget dropTarget = new DropTarget(sashForm, DND.DROP_NONE);
dropTarget.setTransfer(transfer);
dragSource.setTransfer(transfer);
lblHello.setBounds(27, 219, 55, 15);
lblHello.setText("Hello");
dragSource.addDragListener(new DragSourceAdapter() {
#Override
public void dragStart(DragSourceEvent event) {
event.doit=true;
}
});
//Drop Event
dropTarget.addDropListener(new DropTargetAdapter() {
#Override
public void drop(DropTargetEvent event) {
System.out.println(event.detail);
//String path = System.getProperty("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");
Image image=new Image(display, "C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");
sashForm.setBackgroundImage(image);
}
});
Easy Way : Drop File on SWT Label with Image (DND)
The drop event occurs when the user releases the mouse over the Drop target.
final CLabel lblNewLabel = new CLabel(parent, SWT.BORDER);
lblNewLabel.setBounds(10, 43, 326, 241);
lblNewLabel.setText("Drop Target");
// Allow data to be copied or moved to the drop target
DropTarget dropTarget = new DropTarget(lblNewLabel, DND.DROP_MOVE| DND.DROP_COPY | DND.DROP_DEFAULT);
// Receive data in Text or File format
final TextTransfer textTransfer = TextTransfer.getInstance();
final FileTransfer fileTransfer = FileTransfer.getInstance();
Transfer[] types = new Transfer[] {fileTransfer, textTransfer};
dropTarget.setTransfer(types);
// DropTargetEvent
dropTarget.addDropListener(new DropTargetAdapter() {
#Override
public void drop(DropTargetEvent event) {
if (textTransfer.isSupportedType(event.currentDataType)) {
String text = (String)event.data;
lblNewLabel.setText(text);
}
if (fileTransfer.isSupportedType(event.currentDataType)){
//clear Label Text
lblNewLabel.setText("");
//list out selected file
String[] files = (String[])event.data;
for (int i = 0; i < files.length; i++) {
String[] split = files[i].split("\\.");
String ext = split[split.length - 1];
// Set Images format "jpg" and "png"
if(ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("png"))
{
lblNewLabel.setImage(SWTResourceManager.getImage(files[i]));
}
else
{
lblNewLabel.setText(files[i]);
}
}//end for loop
}
}//End drop()
});//End addDropListener

Categories

Resources