JavaFX: Setting Drag Done - java

Currently I am developing a program which transfers a list item into another list. It works well with setOnDragExited,if I drag it to another component with the setOnDragExited, it will be dropped. (Which I think the program is rightbecause that is the function of setOnDragExited. But I need the program to only drop the list item when I release the button).
So I have the source which is fieldList and the target which is mainTable
Here is the code for the source, which I have no problem with.
fieldList.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
/* drag was detected, start a drag-and-drop gesture*/
/* allow any transfer mode */
Dragboard db =fieldList.startDragAndDrop(TransferMode.ANY);
/* Put a string on a dragboard */
ClipboardContent content = new ClipboardContent();
content.putString(fieldList.getSelectionModel().getSelectedItem());
db.setContent(content);
event.consume();
}
});
And here is the code which doesn't work with setOnDragDropped but works with setOnDragExited
mainTable.setOnDragDropped(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* data dropped */
System.out.println("onDragDropped");
/* if there is a string data on dragboard, read it and use it */
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasString()) {
ObservableList<String> ls = FXCollections.observableArrayList();
try {
columnLS.add(Resources.getgBCon().getActualName(tableList.getSelectionModel().getSelectedItem())+"."+db.getString());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
success = true;
String base= "";
if(!columnLS.isEmpty()){
for(int i = 0; i<= columnLS.size()-1 ;i++){
if(i == 0){
base = columnLS.get(i);
}else{
base = base + ", " + columnLS.get(i);
}
}
}
columnQuery = base;
me.refreshSQLQuery(columnQuery,getTableQuery(),filterQuery,groupQuery,sortQuery);
}
/* let the source know whether the string was successfully
* transferred and used */
event.setDropCompleted(true);
event.consume();
}
});
So far I didn't find anything that relates to my problem, on those that are remotely related I found, I have tried but to no avail.
Thank you Stack Overflow.
I have added setOnDragEntered. It seems it still didn't work. Is there a difference between setOnDrag and setOnMouseDrag?
mainTable.setOnDragEntered(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
System.out.println("onDragEntered");
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
});
I have also tried TransferMode.ANY but to no avail.
Solution:
Used mainTable.setOnDragOver instead of mainTable.setOnDragEntered

Related

Java RCP toolbar spoiled

The toolbar runaway from expected result the first button suppose located at the last button.. the rest of the button suppose display below the menu bar, this happening while change the eclipse version and currently i am using
eclipse luna 4.4.2
this line seem not helping
IToolBarManager toolbar = new ToolBarManager(SWT.FLAT | SWT.LEFT);
In eclipse 3.7 those functions like openWorkbenchWindow (Workbench.class), restoreWorkbenchWindow will be call and end up to function like arrangeToolbar will be trigger
/*
* (non-Javadoc) Method declared on IWorkbench.
*/
public IWorkbenchWindow openWorkbenchWindow(final String perspID,
final IAdaptable input) throws WorkbenchException {
// Run op in busy cursor.
final Object[] result = new Object[1];
BusyIndicator.showWhile(null, new Runnable() {
public void run() {
try {
result[0] = busyOpenWorkbenchWindow(perspID, input);
} catch (WorkbenchException e) {
result[0] = e;
}
}
});
if (result[0] instanceof IWorkbenchWindow) {
return (IWorkbenchWindow) result[0];
} else if (result[0] instanceof WorkbenchException) {
throw (WorkbenchException) result[0];
} else {
throw new WorkbenchException(
WorkbenchMessages.Abnormal_Workbench_Conditi);
}
}
/*
* (non-Javadoc)
*
* #see org.eclipse.ui.IWorkbench#restoreWorkbenchWindow(org.eclipse.ui.IMemento)
*/
IWorkbenchWindow restoreWorkbenchWindow(IMemento memento)
throws WorkbenchException {
WorkbenchWindow newWindow = newWorkbenchWindow();
newWindow.create();
windowManager.add(newWindow);
// whether the window was opened
boolean opened = false;
try {
newWindow.restoreState(memento, null);
newWindow.fireWindowRestored();
newWindow.open();
opened = true;
} finally {
if (!opened) {
newWindow.close();
}
}
return newWindow;
}
void updatePerspectiveBar() {
// Update each item as the text may have to be shortened.
IContributionItem[] items = perspectiveBar.getItems();
for (int i = 0; i < items.length; i++) {
items[i].update();
}
// make sure the selected item is visible
perspectiveBar.arrangeToolbar();
setCoolItemSize(coolItem);
perspectiveBar.getControl().redraw();
if (getControl() != null)
getControl().pack(true);
}
however, eclipse 4.4.2 does not contains above functions anymore
the functions contents are different and restoreWorkbenchWindow are no longer support.
/*
* (non-Javadoc) Method declared on IWorkbench.
*/
#Override
public IWorkbenchWindow openWorkbenchWindow(String perspectiveId, IAdaptable input)
throws WorkbenchException {
IPerspectiveDescriptor descriptor = getPerspectiveRegistry().findPerspectiveWithId(
perspectiveId);
try {
MWindow window = BasicFactoryImpl.eINSTANCE.createTrimmedWindow();
return openWorkbenchWindow(input, descriptor, window, true);
} catch (InjectionException e) {
throw new WorkbenchException(e.getMessage(), e);
}
}
public WorkbenchWindow openWorkbenchWindow(IAdaptable input, IPerspectiveDescriptor descriptor,
MWindow window, boolean newWindow) {
return (WorkbenchWindow) createWorkbenchWindow(input, descriptor, window, newWindow);
}
any advise or way to fix the issues i am facing? thanks you.

One program, different on multiple computers

First of all, I want to ask you to ask as much information as possible to me to be able to help me out.
I've been creating an automatic reminder system which is able to create the reminder in PDF then automatically send it to the clients which you've chosen to be reminded.
The program is working perfectly fine, but once I try to start it on another computer, it does not work anymore. The following problems occur:
On one computer in Eclipse it does not even open the frame which handles the user input (telling the program which clients have to be reminded). The code is given below. An interesting point here is that I've tried to print a line if the actionPerformed method is running. It does NOT appear at all. So for some reason it is not listening to that whole method.
if(starter.getAccess().equals("admin") || starter.getAccess().equals("god")){
menu = new JMenu("Aanmaningen");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Debiteuren aanmanen");
menuBar.add(menu);
menu.addSeparator();
ButtonGroup group2 = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("Pyxis Distribution B.V.");
rbMenuItem.setSelected(false);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group2.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem.addActionListener(new ActionListener() {
#SuppressWarnings("static-access")
#Override
public void actionPerformed(ActionEvent arg0) {
chosenComp = true;
f.getContentPane().add(new Main());
f.revalidate();
f.repaint();
Distrscherm obj = new Distrscherm();
obj.plannerJTable();
}
});
On the other computers it was jarred and did open the menu, but did the JComboBox did not automatically complete the searchterms. It neither sent the mail. When clicking on the button save and send it didn't do anything. The codes are shown below.
This is the code which handles automatic completion (pretty basic code)
public AutoComboBox() {
setModel(new DefaultComboBoxModel(myVector));
setSelectedIndex(-1);
setEditable(true);
JTextField text = (JTextField) this.getEditor().getEditorComponent();
text.setFocusable(true);
text.setText("");
text.addKeyListener(new ComboListener(this, myVector));
setMyVector();
}
/**
* set the item list of the AutoComboBox
* #param patternExamples an String array
*/
public static void setKeyWord(Object[] patternExamples) {
AutoComboBox.keyWord = patternExamples;
setMyVectorInitial();
}
private void setMyVector() {
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
}
private static void setMyVectorInitial() {
myVector.clear();
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
This is the code which handles the SAVE button
#Override
public void actionPerformed(ActionEvent e) {
#SuppressWarnings("unused")
Writer obj1 = new Writer(getTableData(table), "./planningdagelijks/week.csv");
for(int i =0; i < model.getRowCount(); i++) {
Datareader.Runner(model.getValueAt(i, 0));
internalfile obj2 = new internalfile();
obj2.intern();
try {
maildata.Reader((String)model.getValueAt(i, 0));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Pdfgenerator.Filegenerator((String)model.getValueAt(i, 0));
}
}
});

Java Intermec ITCScan failed to load

I'm trying to implement a Barcode Reader for a CK71 ATEX Intermec Scanner. The operating system is Windows Embedded Handheld 6.5 and as JVM I'm using phoneME Personal Profile. I did install the DC_Java_WM6_Armv4i.cab (see the picture)
When I run the code below I get the following error: ITCScan failed to load. java.lang.UnsatisfiedLinkError: no ITCScan.dll in java.library.path
How can I fix this error? I've tried everything.
Note that before, I was using CreME JVM and everything was working fine. I gave up CreME when my 30 days evaluation version expired.
The content of the .lnk file (instead of myProject.MainClass are the real names of course):
255#"\Program Files\pMEA PP\bin\cvm.exe" "-Xopt:stdioPrefix=\My Documents,useConsole=false" -cp "\My Documents\Trasabilitate.jar;\My Documents\DataCollection.jar" myProject.MainClass
Here is the complete code:
/*
* BarcodeSample.java
*
* COPYRIGHT (c) 2004 INTERMEC TECHNOLOGIES CORPORATION, ALL RIGHTS RESERVED
*/
import java.awt.*;
import com.intermec.datacollection.*;
/**
* This sample demonstrates using the BarcodeReader class to
* read barcode data into a text field.
*/
public class BarcodeSample extends Frame implements BarcodeReadListener
{
BarcodeReader bcRdr;
TextField txtFieldData;
Button btnClose;
Label labelStatus;
public BarcodeSample(String aTitle)
{
super(aTitle);
initComponents();
try
{
bcRdr = new BarcodeReader();
bcRdr.addBarcodeReadListener(this);
// Starts asynchronous barcode read
bcRdr.threadedRead(true);
}
catch (BarcodeReaderException e)
{
System.out.println(e);
labelStatus.setText(e.getMessage());
//*****
//* Since m_labelStatus was not initialized with text,
//* doLayout() is required on some platforms in order
//* to show the new label text for the first setText()
//* call.
//*****
doLayout();
}
}
private void initComponents()
{
setLayout(new FlowLayout());
txtFieldData = new TextField(20);
add(txtFieldData);
btnClose = new Button("Close");
add(btnClose);
labelStatus = new Label();
add(labelStatus);
btnClose.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
exitApp();
}
});
btnClose.addKeyListener(new java.awt.event.KeyListener() {
public void keyPressed(java.awt.event.KeyEvent e) {
if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER)
{
exitApp();
}
}
public void keyReleased(java.awt.event.KeyEvent e) {}
public void keyTyped(java.awt.event.KeyEvent e) {}
});
}
/**
* This method is invoked when the BarcodeReadEvent occurs.
*/
public void barcodeRead(BarcodeReadEvent aBarcodeReadEvent)
{
/**
* Uses EventQueue.invokeLater to ensure the UI update
* executes on the AWT event dispatching thread.
*/
final String sNewData = aBarcodeReadEvent.strDataBuffer;
EventQueue.invokeLater(new Runnable() {
public void run() {
// Displays the scanned data in the text field
txtFieldData.setText(sNewData);
}
});
}
public void exitApp()
{
if (bcRdr != null)
bcRdr.dispose(); // Release system resources used by BarcodeReader
setVisible(false);
dispose(); // Dispose the frame
System.exit(0);
}
public static void main(String[] args)
{
final BarcodeSample asyncReader =
new BarcodeSample("Barcode Sample");
asyncReader.addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(java.awt.event.WindowEvent e)
{
asyncReader.exitApp();
};
});
asyncReader.setVisible(true);
}
}
I finally got it to work. I found out what my java path was using the snippet here (I'll post it below in case something happens to the link):
Properties p = System.getProperties();
Enumeration keys = p.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = (String)p.get(key);
System.out.println(key + ": " + value);
}
And then I added my ITCScan.dll to the folder where java.library.path was set (in my case, \ProgramFiles\pMEA PP\bin.
I don't know if this is the most elegant solution, but it works. Hope it'll help somebody someday.

JavaFx Drag and Drop a file INTO a program

Hey there community I was wondering if is possible to create a program that allows for the user to Drag a file from anywhere on there hard drive (the desktop, documents folder, videos folder) and drop it into the window of the program.
I am creating a media player and I want to be able to play a video by dragging and dropping a MP4 into the window. Do I need to store the file in a variable, or just the location of the file into a variable. Also, it is important I keep support for cross platform.
I am using JavaFx with java 7 update 79 jdk.
Thanks in advance.
Here is a simple drag and drop example that just sets the file name and location. Drag files to it and it shows their name and location. Once you know that it should be a completely separate matter to actually play the file. It is primarily taken from Oracle's documentation: https://docs.oracle.com/javafx/2/drag_drop/jfxpub-drag_drop.htm
A minimal implementation needs two EventHandler s set OnDragOver and OnDragDropped.
public class DragAndDropTest extends Application {
#Override
public void start(Stage primaryStage) {
Label label = new Label("Drag a file to me.");
Label dropped = new Label("");
VBox dragTarget = new VBox();
dragTarget.getChildren().addAll(label,dropped);
dragTarget.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
if (event.getGestureSource() != dragTarget
&& event.getDragboard().hasFiles()) {
/* allow for both copying and moving, whatever user chooses */
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
event.consume();
}
});
dragTarget.setOnDragDropped(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasFiles()) {
dropped.setText(db.getFiles().toString());
success = true;
}
/* let the source know whether the string was successfully
* transferred and used */
event.setDropCompleted(success);
event.consume();
}
});
StackPane root = new StackPane();
root.getChildren().add(dragTarget);
Scene scene = new Scene(root, 500, 250);
primaryStage.setTitle("Drag Test");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
When working with Drag and Drop events, you could try the following:
Obtain a Dragboard-object of the DragEvent and work with the method getFiles:
private void handleDragDropped(DragEvent event){
Dragboard db = event.getDragboard();
File file = db.getFiles().get(0);
}
I solved this by adding two event handlers. One for DragDropped event and the other for DragOver event.
e.g:
#FXML
void handleFileOverEvent(DragEvent event)
{
Dragboard db = event.getDragboard();
if (db.hasFiles())
{
event.acceptTransferModes(TransferMode.COPY);
}
else
{
event.consume();
}
}
#FXML
void handleFileDroppedEvent(DragEvent event)
{
Dragboard db = event.getDragboard();
File file = db.getFiles().get(0);
handleSelectedFile(file);
}
Else it did not work for me, dragging the file over my pane, didn't trigger anything.

JavaFx Drag and Drop between 2 Swing JFXPanels not fully working?

I have a Swing application, and inside my JFrame there are 2 JFXPanels, containing 2 JavaFx Nodes, a TableView and a WebView. The table contains a list of urls (think of it like a bookmarks list). I want the user to drag a url from the table on the left to the webview on the right. I set up drag-and-drop events according to the JavaFx tutorial and answers to previous drag-and-drop questions here. However, the 2 JFXPanels seem to not be able to communicate with each other.
I can drag URLs from the table to outside of my application (e.g. my web browser) and that works OK.
I can also drop URLs from the outside (e.g. copied from by web browser's address bar) to the web view and it loads them correctly too.
But when I drag URLs from the table, and try to drop them on the WebView, I always get an empty dragboard on the target side (I tried using both the String and the Url data formats, but both come back as null, also the event.getGestureSource() comes back as null), eventhough the source fills it correctly (watched it step-by-step with the debugger).
Could this be a side-effect of the fact that this is between 2 JFXPanels, and there is Swing in between which handles drag-and-drop using a different API? By the way, I do not have any other drag-and-drop code in the remaining Swing part of the application, so not mixing the two event models.
Thanks in advance for any pointers, tips or ideas.
Sample code snippets of my event handlers below:
(using JavaFx2.2, Jdk 1.7.0_40, on Windows 7 64 bit machine)
/* on the source side, the TableView */
// initiate drag
table.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
/* Put the selected file or url on the dragboard */
MyObject tableItem = table.getSelectionModel().getSelectedItem();
String item = tableItem.getUrlString();
if (item != null)
{
Dragboard db = table.startDragAndDrop(TransferMode.COPY);
ClipboardContent content = new ClipboardContent();
content.putString(item);
content.putUrl(item);
db.setContent(content);
}
event.consume();
}
});
table.setOnDragDone(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event)
{
event.consume();
}
});
/* on the target side, the WebView */
webView.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if (event.getGestureSource() != webView && (db.hasUrl() || db.hasString())) {
event.acceptTransferModes(TransferMode.ANY);
} else {
event.consume();
}
}
});
// handle drop
webView.setOnDragDropped(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
String urlDropped = db.getUrl();
if (urlDropped == null)
urlDropped = db.getString();
if (urlDropped != null)
{
webView.getEngine().load(urlDropped);
}
event.setDropCompleted(success);
event.consume();
}
});

Categories