Drop File on SWT Label with Image (DND) - java

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

Related

How to get contents to show up inside a ScrolledComposite

I am creating a legend view and inside the shell is supposed to have a rectangle followed by a label describing the color. I was able to get the view to work using just a normal composite but the legend continues beyond the screen and no way of see it without making the window larger. I am trying to use a scrolledComposite view for my shell but when I execute the program, nothing appears.
public void createPartControl(Composite parent)
{
display = parent.getDisplay();
parent.setLayout(new FillLayout());
sc = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL);
LegendView.composite = new Composite(sc, SWT.NONE);
RowLayout layout = new RowLayout();
layout.wrap = true;
layout.spacing = 5;
composite.setLayout(layout);
}
public static void addRectangle(String legendMessage)
{
final String propId = legendMessage;
final String[] s = propId.split(",");
if (display != null)
{
display.syncExec(new Runnable()
{
#Override
public void run()
{
// Creating the color using the RBG values
final Color color =
new Color(display, Integer.parseInt(s[0]), Integer.parseInt(s[1]), Integer.parseInt(s[2]));
// Creating a canvas for which the rectangle can be drawn on
Canvas canvas = new Canvas(composite, SWT.NONE);
// Maybe set the bounds of the canvas
canvas.addPaintListener(new PaintListener()
{
public void paintControl(PaintEvent e)
{
e.gc.drawRectangle(1, 1, 50, 60);
e.gc.setBackground(color);
e.gc.fillRectangle(2, 2, 49, 59);
}
});
// Disposing the color after it has been used
canvas.addDisposeListener(new DisposeListener()
{
public void widgetDisposed(DisposeEvent e)
{
color.dispose();
}
});
// Creating a label and setting the font
Label label = new Label(composite, SWT.NULL);
Font boldFont = new Font( label.getDisplay(), new FontData( "Arial", 12, SWT.BOLD ) );
label.setFont( boldFont );
label.setText(s[3]);
composite.redraw();
composite.layout(true);
sc.setContent(composite);
}
});
}
}
I am calling add rectangle in a different class. I am fairly new at using SWT and after looking at examples and reading the docs for scrolled Composite, this is what I interpreted it as. Any help would be very appreciated.
You haven't told the ScrolledComposite how to manage the size. You must either call setSize or setMinSize. For this you probably want:
sc.setExpandHorizontal(true);
sc.setExpandVertical(true);
sc.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));

Drag and Drop svg file in a canvas

I have created an editor, in which I display a canvas. I would like to allow DnD for svg files.
The fact is that I allow to drop files with this part of code :
int operations = DND.DROP_COPY | DND.DROP_MOVE;
Transfer[] types = new Transfer[]{FileTransfer.getInstance()};
DropTarget dt = new DropTarget(parent, operations);
dt.setTransfer(types);
dt.addDropListener(new DropTargetAdapter() {
public void drop(DropTargetEvent event) {
//ToDo
}
But it allows any type of files, and I only want .svg files.
How could I create a condition, which will check if the file dropped is a .svg file or not, and if it is, create a new canvas with the imported file ?
I would like to recover the path of the dropped file too, any idea of how I could do that ?
I don't really know how I could restrict the imported file to svg.
Assuming that all your files have a valid .svg extension, check the file extension in the adapter and only use those files that have the right extension while ignoring files with other extensions.
Then do what you need to do with the files:
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Stackoverflow");
shell.setLayout(new FillLayout());
Label label = new Label(shell, SWT.NONE);
DropTarget target = new DropTarget(label, DND.DROP_DEFAULT | DND.DROP_MOVE | DND.DROP_COPY);
Transfer[] transfers = new Transfer[]{FileTransfer.getInstance()};
target.setTransfer(transfers);
target.addDropListener(new DropTargetAdapter()
{
public void drop(DropTargetEvent event)
{
if (event.data == null)
{
event.detail = DND.DROP_NONE;
return;
}
String[] paths = (String[]) event.data;
List<File> files = new ArrayList<>();
for (String path : paths)
{
int index = path.lastIndexOf(".");
if (index != -1)
{
String extension = path.substring(index + 1);
if (Objects.equals(extension, "svg"))
files.add(new File(path));
}
}
System.out.println(files);
}
});
shell.pack();
shell.open();
shell.setSize(400, 300);
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}

List all the installed programs that can open a specific file type in java

Is it possible to get the list of all the applications that can open a certain file type from the OS in Java?
For eg, list of all the applications that can open a .txt or .pdf file.
You should check the example of the JFace Eclipse plugin that is here: http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/Showstheextensionsonthesystemandtheirassociatedprograms.htm
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.*;
/**
* This class shows the extensions on the system and their associated programs.
*/
public class ShowPrograms {
/**
* Runs the application
*/
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Show Programs");
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
/**
* Creates the main window's contents
*
* #param shell the main window
*/
private void createContents(Shell shell) {
shell.setLayout(new GridLayout(2, false));
// Create the label and combo for the extensions
new Label(shell, SWT.NONE).setText("Extension:");
Combo extensionsCombo = new Combo(shell, SWT.BORDER | SWT.READ_ONLY);
extensionsCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Create the label and the
new Label(shell, SWT.NONE).setText("Program:");
final Label programName = new Label(shell, SWT.NONE);
programName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Fill the combo with the extensions on the system
String[] extensions = Program.getExtensions();
for (int i = 0, n = extensions.length; i < n; i++) {
extensionsCombo.add(extensions[i]);
}
// Add a handler to get the selected extension, look up the associated
// program, and display the program's name
extensionsCombo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
Combo combo = (Combo) event.widget;
// Get the program for the extension
Program program = Program.findProgram(combo.getText());
// Display the program's name
programName.setText(program == null ? "(None)" : program.getName());
}
});
// Create a list box to show all the programs on the system
List allPrograms = new List(shell, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL
| SWT.V_SCROLL);
GridData data = new GridData(GridData.FILL_BOTH);
data.horizontalSpan = 2;
allPrograms.setLayoutData(data);
// Put all the known programs into the list box
Program[] programs = Program.getPrograms();
for (int i = 0, n = programs.length; i < n; i++) {
String name = programs[i].getName();
allPrograms.add(name);
allPrograms.setData(name, programs[i]);
}
// Add a field for a data file
new Label(shell, SWT.NONE).setText("Data File:");
final Text dataFile = new Text(shell, SWT.BORDER);
dataFile.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// Double-clicking a program in the list launches the program
allPrograms.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent event) {
List list = (List) event.widget;
if (list.getSelectionCount() > 0) {
String programName = list.getSelection()[0];
Program program = (Program) list.getData(programName);
program.execute(dataFile.getText());
}
}
});
// Let them use launch instead of execute
Button launch = new Button(shell, SWT.PUSH);
data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
launch.setLayoutData(data);
launch.setText("Use Program.launch() instead of Program.execute()");
launch.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
// Use launch
Program.launch(dataFile.getText());
}
});
}
/**
* The application entry point
*
* #param args the command line arguments
*/
public static void main(String[] args) {
new ShowPrograms().run();
}
}

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

JFace ApplicationWindow: createContents isn't working

I'm attempting to create a window that is divided into three parts. A non-resizable header and footer and then a content area that expands to fill the remaining area in the window. To get started, I created the following class:
public class MyWindow extends ApplicationWindow {
Color white;
Font mainFont;
Font headerFont;
public MyWindow() {
super(null);
}
protected Control createContents(Composite parent) {
Display currentDisplay = Display.getCurrent();
white = new Color(currentDisplay, 255, 255, 255);
mainFont = new Font(currentDisplay, "Tahoma", 8, 0);
headerFont = new Font(currentDisplay, "Tahoma", 16, 0);
// Main layout Composites and overall FillLayout
Composite container = new Composite(parent, SWT.NO_RADIO_GROUP);
Composite header = new Composite(container, SWT.NO_RADIO_GROUP);
Composite mainContents = new Composite(container, SWT.NO_RADIO_GROUP);;
Composite footer = new Composite(container, SWT.NO_RADIO_GROUP);;
FillLayout containerLayout = new FillLayout(SWT.VERTICAL);
container.setLayout(containerLayout);
// Header
Label headerLabel = new Label(header, SWT.LEFT);
headerLabel.setText("Header");
headerLabel.setFont(headerFont);
// Main contents
Label contentsLabel = new Label(mainContents, SWT.CENTER);
contentsLabel.setText("Main Content Here");
contentsLabel.setFont(mainFont);
// Footer
Label footerLabel = new Label(footer, SWT.CENTER);
footerLabel.setText("Footer Here");
footerLabel.setFont(mainFont);
return container;
}
public void dispose() {
cleanUp();
}
#Override
protected void finalize() throws Throwable {
cleanUp();
super.finalize();
}
private void cleanUp() {
if (headerFont != null) {
headerFont.dispose();
}
if (mainFont != null) {
mainFont.dispose();
}
if (white != null) {
white.dispose();
}
}
}
And this results in an empty window when I run it like this:
public static void main(String[] args) {
MyWindow myWindow = new MyWindow();
myWindow.setBlockOnOpen(true);
myWindow.open();
Display.getCurrent().dispose();
}
What am I doing wrong that I don't see three labels the way I'm trying to display them? The createContents code is definitely being called, I can step through it in Eclipse in debug mode.
Apparently, I needed to set the size and location of the labels to get them to appear.

Categories

Resources