Drag and drop from javaFX scene to windows explorer - drag-and-drop

Is there any way to Drag and drop from javaFX scene to windows explorer?

Yes there is
You should use the onDragDetected function to start your dragEvent and the onDragDone function for doing whatever you want after finishing the drag & drop.
Here an example:
final Text source = new Text(50, 100, "DRAG ME");
source.setOnDragDetected(new EventHandler <MouseEvent>() {
public void handle(MouseEvent event) {
/* drag was detected, start drag-and-drop gesture*/
System.out.println("onDragDetected");
/* allow any transfer mode */
Dragboard db = source.startDragAndDrop(TransferMode.ANY);
/* put a string on dragboard */
ClipboardContent content = new ClipboardContent();
content.putString(source.getText());
db.setContent(content);
event.consume();
}
source.setOnDragDone(new EventHandler <DragEvent>() {
public void handle(DragEvent event) {
/* the drag-and-drop gesture ended */
System.out.println("onDragDone");
/* if the data was successfully moved, clear it */
if (event.getTransferMode() == TransferMode.MOVE) {
source.setText("");
}
event.consume();
}
});

Related

How to select a component on jframe?

How to select a JTextArea on JButton click?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.setEditable(true);
jTextArea1.setForeground(Color.BLACK);
//*******************************************************
jframe.setselected(jTextArea1); // I need such function!
//*******************************************************
}
By select I assume you mean transfer focus to the JTextArea. If so you can request focus of you text area with the following.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.setEditable(true);
jTextArea1.setForeground(Color.BLACK);
/*******************************************************
jTextArea1.requestFocusInWindow();
/*******************************************************
}

Generating check boxes dynamically, Netbeans

I am developing a desktop application in which I want Admin have option to delete users, for which I planned that whenever Admin clicks on 'delete users' button a new tab will open in which check boxes with the name of all existing users in my database should appear(so that he can delete multiple users simultaneously); so basically I need to generate dynamic check boxes as per my database.
I am using Netbeans 7.0.1, jdk 1.6, sqlite3.
After searching on google I got two links which match to my problem:
http://www.coderanch.com/t/345949/GUI/java/create-dynamic-checkboxes#2805277
Creating dcheckbox dynamically in Java-NetBeans
I have tried to follow the code from above first link but it does not working for me properly. What I does is just created new JFrame in netbeans and called a method inside constructor which create checkboxes as per needed, method's code is as below:
public class Work extends javax.swing.JFrame {
/** Creates new form Work */
public Work() {
initComponents();
checks = new java.util.ArrayList<>();
createCheckboxes();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void createCheckboxes(){
panel = new javax.swing.JPanel();
this.add(panel);
for(int i = 0; i<4; i++){
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
panel.add(box);
checks.add(box);
panel.revalidate();
panel.repaint();
}
panel.setVisible(true);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
private java.util.ArrayList <javax.swing.JCheckBox> checks;
private javax.swing.JPanel panel;
}
The output is just a blank frame. Please help me to know where I am wrong!!
And yes this code is not connected to database yet, once it will work then I can modify it to work with database.
Also is their any other betterway to accomplish my task or am on right path?`
I think it might help if u call the following function whenever to wanna create a new checkbox..
public class CheckBox extends JFrame{
//private static final long serialVersionUID = 1L;
public CheckBox() {
// set flow layout for the frame
this.getContentPane().setLayout(new FlowLayout(FlowLayout.TRAILING, 50, 20)); //(default) centered alignment and a default 5-unit horizontal and vertical gap.
JCheckBox checkBox1 = new JCheckBox("Checkbox 1");
checkBox1.setSelected(true);
JCheckBox checkBox2 = new JCheckBox("Checkbox 2", true);
JCheckBox checkBox3 = new JCheckBox("Checkbox 3");
// add checkboxes to frame
add(checkBox1);
add(checkBox2);
add(checkBox3);
}
private static void createAndShowGUI() {
//Create and set up the window.
//JFrame frame = new CreateCheckedUncheckedJCheckBox();
CheckBox cb = new CheckBox();
//Display the window.
cb.pack();
cb.setVisible(true);
cb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You add the new checkboxes as if your frame was using some simple layout such as FlowLayout, but it is not - it is using GroupLayout - see the generated initComponents() method.
If you want to handle ALL components in the frame dynamically, you can do this (it is better to create an empty class file and then paste the code below; do not ask NB to create a JFrame as it would again create a form to be designed in the visual designer; if you still do it then r-click it and change the layout to something simpler):
public class Work extends javax.swing.JFrame {
private java.util.List <javax.swing.JCheckBox> checks = new java.util.ArrayList<>();;
public Work() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new java.awt.FlowLayout()); // simply put the components next to each other
createCheckboxes();
}
private void createCheckboxes(){
for(int i=0; i<4; i++) {
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
add(box);
checks.add(box);
}
pack(); // this will tell the JFrame's panel to layout all the components
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
}
Or you can design part of your frame with the visual designer and then add the checkboxes. In that case add an empty panel in the designer, set the panel's layout to something like flow or grid layout and then add the checkboxes to that panel from your code in the same way as above.
You validate needs to be called only if the panel/frame is already visible. Calling pack works even then, but might change the size of the frame. Also validating can be done after all components were added not after adding each one.
To add check boxes or any other component dynamically in Netbeans JFrame one need to manage Layout Managers, by default netbeans frames use Free Design Layout, follow steps below:
Create blank JFrame -->Add Jpanel to it-->right click to the panel, select setLayout and change it to GridLayout.
Now we are free to add ant components on this panel.
Also don't forgate to add revalidate() and repaint() methods.
This worked for me.

JavaFX Dragboard setContent interfering with setOnMouseDragged?

I would like to use drag and drop in JavaFX and have a feature where you can visually see the item being dragged. I've implemented what I thought would be a working solution, but there seems to be an issue with the API.
According to the API startDragAndDrop(TransferMode...) MUST be initialized inside setOnDragDetected. This is where I use a Dragboard to store content I'd like to transfer to another node.
EDIT: This appears to have something to do with the TrasferMode. If I use TransferMode.NONE there is no issue, but use of COPY, ANY, LINK always results in this problem.
But calling dragBoard.setContent(some clipboard content) only allows very small increments of movement with the mouse (a max of 4 pixels in any direction!). Removing this line of code, I can then drag the item and see it being dragged anywhere, but of course, I then can't store clipboard content.
The problem I see is that setOnMouseDragged(..) gets called before setOnDragDetected! It doesn't make much sense why setOnMouseDragged gets run before setOnDragDetected...
Is there something obvious to you in my code that's maybe causing a problem? I'd simply like to be able to see the imgView moving when dragging and be able to drop it on a target as usual, with the clipboard content.
EDIT 2: Updated code below to reflect using only Drag events, rather than Drag and Mouse events. Using both caused issues. The problem that still remains is that I'm unable to drop on a target, since using setOnDragOver makes the dragged node always right below the cursor.
protected ImageView initImageView(Image img){
final Pane ldzPane = GameBoard.getInstance().getLDZpane();
final ObjectProperty<Point2D> dragAnchor = new SimpleObjectProperty<>();
final ImageView imgView = new ImageView(img);
final DoubleProperty initX = new SimpleDoubleProperty();
final DoubleProperty initY = new SimpleDoubleProperty();
final DoubleProperty dragX = new SimpleDoubleProperty();
final DoubleProperty dragY = new SimpleDoubleProperty();
final DoubleProperty newXPosition = new SimpleDoubleProperty();
final DoubleProperty newYPosition = new SimpleDoubleProperty();
final int buffer = 3;
imgView.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
initX.set(imgView.getTranslateX());
initY.set(imgView.getTranslateY());
dragAnchor.set(new Point2D(event.getSceneX(), event.getSceneY()));
ClipboardContent content = new ClipboardContent();
content.putString(RHSIconizedToken.this.tokenLookupInfo());
Dragboard db = imgView.startDragAndDrop(TransferMode.ANY);
db.setContent(content);
event.consume();
}
});
imgView.setOnDragOver(new EventHandler<DragEvent>(){
#Override
public void handle(DragEvent event) {
imgView.toFront();
dragX.set(event.getSceneX() - dragAnchor.get().getX());
dragY.set(event.getSceneY() - dragAnchor.get().getY());
imgView.setOpacity(0.5);
newXPosition.set(initX.get() + dragX.get());
newYPosition.set(initY.get() + dragY.get());
//if( (Math.abs((newXPosition.get() - ldzPane.getWidth())) <= ldzPane.getWidth() + startX + buffer) &&
// ((newXPosition.get() + startX + imgView.getImage().getWidth()+ buffer)<= ldzPane.getWidth()))
imgView.setTranslateX(newXPosition.get());
//if( (Math.abs((newYPosition.get() - ldzPane.getHeight())) <= ldzPane.getHeight() + startY + buffer) &&
// ((newYPosition.get() + startY + imgView.getImage().getHeight()+ buffer)<= ldzPane.getHeight()))
imgView.setTranslateY(newYPosition.get());
event.consume();
}
});
imgView.setOnDragDone(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
LinkedList<RHSIconizedToken> iTokens = GameBoard.getInstance().getTokenBayItokens();
if (event.getTransferMode() == TransferMode.MOVE) {
RHSIconizedToken element = iTokens.remove(index);
iTokens.add(index, new RHSIconizedToken(element.getImage(), new SourceToken("removed", "removed"), index));
imgView.setVisible(false);
GameBoard theGameBoard = GameBoard.getInstance();
GUI theGUI = GUI.getInstance();
//was this the last one removed from the rhs?
//if so we need to signal the CompileButton to be turned on!
if(theGameBoard.isRHSempty())
theGUI.enableCompileButton();
else
theGUI.disableCompileButton();
}
event.consume();
}
});
imgView.setOnMouseEntered(new EventHandler <MouseEvent>() {
public void handle(MouseEvent event) {
imgView.setEffect(new Glow(0.5));
event.consume();
}
});
imgView.setOnMouseExited(new EventHandler <MouseEvent>() {
public void handle(MouseEvent event) {
imgView.setEffect(new Glow(0.0));
imgView.setOpacity(1);
event.consume();
}
});
return imgView;
}
Java 8 is scheduled to ship with more support for visual drag and drop. DragBoard's setDragView (Image, XOffset, YOffset) method works great, and is available with the Java 8 beta.
imgView.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
ClipboardContent content = new ClipboardContent();
content.putString(RHSIconizedToken.this.tokenLookupInfo());
Dragboard db = imgView.startDragAndDrop(TransferMode.ANY);
db.setDragView(image, 7, 7);
db.setContent(content);
event.consume();
}
});
I think this would help you:
DraggablePanelsExample.java
I usedd this for my Panels too, and it works for ImageView like a charm.
EDIT:
You are combining this false! You can not combine DragDetected with MouseDragged.
If you start dragging in JavaFX, the mouseevents does not get fired anymore.
If you want a Drag-Board-String then simply save you String in you class.
ps: replace DragDone with MouseReleased

Capturing mouse events on horizontal panel in GWT

Is there a way to capture mouse events on a horizontal panel in gwt ?
I am trying to capture mousedown or onclick events but m not able to get it working. This is what i have done so far
final HorizontalPanel container = new HorizontalPanel() {
#Override
public void sinkEvents(int eventBitsToAdd) {
// TODO Auto-generated method stub
super.sinkEvents(Event.ONCLICK);
}
#Override
public void onBrowserEvent(final Event event) {
// TODO Auto-generated method stub
super.onBrowserEvent(event);
if (DOM.eventGetType(event) == Event.ONCLICK) {
System.out.println("event type -->> " + event.getType());
}
/*if(Event.ONMOUSEDOWN == arg0.getTypeInt())
System.out.println("event type -->> " + arg0.getType());*/
}
};
I have no clue why this doesn't work.
any help would be appreciated.
Thanks
Instead of manually sinking and reading events, you could consider using Widget#addDomHandler():
HorizontalPanel container = new HorizontalPanel();
ClickHandler cHandler = new ClickHandler(){ /* ... */ };
MouseDownHandler mdHandler = new MouseDownHandler(){ /* ... */ };
container.addDomHandler(cHandler, ClickEvent.getType());
container.addDomHandler(mdHandler, MouseDownEvent.getType());
You can use FocusPanel. For example:
HorizontalPanel yourContainer = new HorizontalPanel();
FocusPanel wrapper = new FocusPanel();
wrapper.add(yourContainer );
wrapper.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
// Handle the click
}
});

GWT 2.2.0 PopupPanel autoHide on TOUCH Events

PopupPanel is a class within GWT written (akhem) a long time ago (which is why it sucks so much) that allows for showing popups with content. One of the options is autoHide where if there's a certain event outside of the popup it closes the popup. It works well on anything EXCEPT Safari Mobil (SM). Reason is SM doesn't fire click events on touch. It fires touch events. PopupPanel is hard coded to look for ClickEvents.
Specifically, the code says:
case Event.ONMOUSEDOWN:
...
if (!eventTargetsPopupOrPartner && autoHide) {
hide(true);
...
Obviously this isn't complete and it should also include Event.ONTOUCHSTART
Problem is, all the methods and fields are private so I cannot add this functionality. That's a big boo-boo on the part of GWT team but not really a concern since I could just make my own class and copy contents of PopupPanel. The big problem is that nativeEventPreview doesn't capture Touch Events!
I tried adding the following to Event Preview the following:
private static NativePreviewHandler nativePreviewHandler = new NativePreviewHandler() {
public void onPreviewNativeEvent(NativePreviewEvent event) {
Event nativeEvent = Event.as(event.getNativeEvent());
switch (nativeEvent.getTypeInt()) {
case Event.ONTOUCHSTART:
case Event.ONMOUSEDOWN:
EventTarget target = nativeEvent.getEventTarget();
if (!Element.is(target) || !popup.getElement().isOrHasChild(Element.as(target))) {
popup.hide();
} break;
}
}
};
Where 'popup' is the PopupPanel I'm trying to get to close on outside touch events.
Sad thing is it works for mouse down when testing in any other browser on Earth, but not on iPad.
Another thing I tried was adding a TouchStartHandler to the glass of the PopupPanel (the gray looking thing behind it). I war hoping that I could catch the touch events that way, but I was unable to get events to fire on glass since it's attached to DOM in some funny way. My code:
private static class ProperPopupPanel extends PopupPanel {
public ProperPopupPanel() {
super();
}
void setHideOnGlassTouch() {
setGlassEnabled(true);
TouchableLabeThatDoesntCrashOnWrap glass = new TouchableLabeThatDoesntCrashOnWrap(getGlassElement());
glass.addTouchStartHandler(new TouchStartHandler() {
#Override
public void onTouchStart(TouchStartEvent event) {
hide();
}
});
glass.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
hide();
}
});
}
private class TouchableLabeThatDoesntCrashOnWrap extends Label {
public TouchableLabeThatDoesntCrashOnWrap(Element element) {
super(element);
super.onAttach();
}
}
}
In my mind this should work, but it doesn't. I don't know why. Any ideas or suggestions are welcome. Thanks.
Not enough GWT users here... well I made my own class that adds touch handlers through JSNI ...
/**
* Overwrite of the usual PopupPanel with a modification that this one
* works well on touch-enabled browsers.
* #author McTrafik
*/
public class ProperPopupPanel extends PopupPanel {
////////////////////////////////////////////////////////////
/////////// OVERRIDES //////////////////////////////////////
////////////////////////////////////////////////////////////
public ProperPopupPanel() {
super();
setTouchListener();
}
#Override
public void hide() {
super.hide();
removeTouchListener();
}
#Override
public void show() {
super.show();
addTouchListener();
}
////////////////////////////////////////////////////////////
/////////// NANDLERS ///////////////////////////////////////
////////////////////////////////////////////////////////////
protected JavaScriptObject touchHandler;
/**
* Handle a touch event that happened while the popup is open.
* #param event - The event to handle
*/
protected void handleTouchEvent(Event event) {
// Check to see if the events should be firing in the first place.
if (!isShowing()) {
removeTouchListener();
return;
}
// Check if the event happened within the popup
EventTarget target = event.getEventTarget();
if (!Element.is(target) || !getElement().isOrHasChild(Element.as(target))) {
// Stop event if the popup is modal
if (isModal()) event.preventDefault();
// Close the popup if the event happened outside
if (isAutoHideEnabled()) {
hide(true);
removeTouchListener();
}
}
};
/**
* Create a touchHandler that knows how to point to this instance.
* Without it there's a cast exception that happens.
*/
protected native void setTouchListener() /*-{
var caller = this;
this.#[package].ProperPopupPanel::touchHandler = function(event) {
caller.#[package].ProperPopupPanel::handleTouchEvent(Lcom/google/gwt/user/client/Event;)(event);
}
}-*/;
/**
* Add a touch listener that will listen to touch events.
*/
protected native void addTouchListener() /*-{
$doc.addEventListener(
"touchstart",
this.#[package].ProperPopupPanel::touchHandler,
true
);
$doc.addEventListener(
"MozTouchDown",
this.#[package].ProperPopupPanel::touchHandler,
true
);
}-*/;
/**
* Remove the touch listeners
*/
protected native void removeTouchListener() /*-{
$doc.removeEventListener(
"touchstart",
this.#[package].ProperPopupPanel::touchHandler,
true
);
$doc.removeEventListener(
"MozTouchDown",
this.#[package].ProperPopupPanel::touchHandler,
true
);
}-*/;
}