Is there a way to track the value to the position of the mouse while the drag event is still running and if the value is so and so then execute some code code?
Edit: Since this confuses people. I am looking for a way to get real time data of the position of the mouse while dragging. By real time I mean finding the position of the mouse while dragging not on drag beginning or end.
You can use setOnMouseDragged();:
source.setOnMouseDragged(m->{
System.out.println("MouseScreenX:"+m.getScreenX()+", MouseScreenY:"+m.getScreenY());
System.out.println("MouseSceneX:"+m.getSceneX()+", MouseSceneY:"+m.getSceneY());
//Execute some code here(maybe it has to run in a different Thread)
//....code
//....
});
In case you are not comfortable with lambda expressions:
source.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
System.out.println("MouseScreenX:" + event.getScreenX() + ", MouseScreenY:" + event.getScreenY());
System.out.println("MouseSceneX:" + event.getSceneX() + ", MouseSceneY:" + event.getSceneY());
// Execute some code here(maybe it has to run in a different
// Thread)
// ...code
// ....
}
});
To execute some code while being in the drag process:
setOnMouseDragged(new EventHandler<TouchEvent>() {
#Override
public void handle(MouseEventevent) {
//your code here
}
});
what exactly do you mean with "and if the value is so and so then execute some code code?"?
Related
I have a problem that probably has a simple fix but I can't seem to get it to work.
I need my program to pause or wait until the user selects either the skip button, or the positive/negative feedback button, before moving on.
I assume this is going to require basic threading, but I'm not sure how to implement it. Any help will be appreacited.
The gui is displayed in a separate class(GUI) and the rest is another class.
The code is sort of messy as it was coded for a Hackfest in 12 hours.
EDIT: Solved it on my own by removing button listeneers and making the variables static.
public void onStatus(Status status) {
//this is a listener from the Twitter4J class. Every time new Tweet comes in it updates.
for (int i = 0; i <= posWords.length; i++) {
if (status.getText().toLowerCase().contains(gui.sCrit.getText())
&& (status.getText().toLowerCase().contains(posWords[i].toLowerCase()))) {
//If the tweet matches this criteria do the following:
String tweet;
Status tempStoreP;
System.out.println("Flagged positive because of " +posWords[i].toLowerCase()+" " + i);
tempStoreP = status;
tweet = tempStoreP.getUser().getName() + ":" + tempStoreP.getText() + " | Flagged as positive \n\r";
gui.cTweet.setText(tweet);
//Write to log
try {
wPLog.append("~" + tweet);
} catch (IOException e) {
}
//Add action listeneer to gTweet.
//here is my problem. I want it to wait until a user has clicked one of these buttons before moving on and getting the next Tweet. It has to pause the thread until a button is clicked then it can only move on to getting another Tweet.
//the problem is that the button listener uses local variables to work.
gui.gTweet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (gui.pTweet.getText().equalsIgnoreCase("")) {
gui.pTweet.setText("Please type a response");
} else if (gui.pTweet.getText().equalsIgnoreCase("Please type a response")) {
gui.pTweet.setText("Please type a response");
} else {
try {
Status sendPTweet = twitter
.updateStatus("#" + tempStoreP.getUser().getScreenName() + " "
+ gui.pTweet.getText());
} catch (TwitterException e1) {
}
}
gui.gTweet.removeActionListener(this);
}
});
//add Aaction listert to sTweet
gui.sTweet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
wPLog.append("Skipped \n\r");
} catch (IOException e1) {
}
gui.sTweet.removeActionListener(this);
}
});
}
Thank you for any help. On a side note, if anyone can tell me why when the button is clicked, it loops and spams people with the same message, it will be helpful. Thank you.
I thought about the multithreading thing and i think it isn't easy enough.
If i were you i would disable all controls except the button that is to click.
Example:
JButton button = new JButton( "Test );
button.setEnabled( false );
The user won't be able to click the button until you use button.setEnabled( true );, if you just disable all controls but the button that should be fine.
In my understand of your problem you can use Multithreading like this:
try{
while(!isSkipClicked){
//your multithreading code
}
//code to move...
}
or
you can use dispose method if you have 2 JFrame.
or
you can use multiple JPanel like while skip button clicked hide pnl1 and show pnl2 using method
pnl1.setvisible(false);
pbl2.setVisible(true);
I assume this is going to require basic threading,
Not true at all.
You say you want your program to "wait." That word doesn't actually mean much to a Swing application. A Swing application is event driven. That is to say, your program mostly consists of event handlers that are called by Swing's top-level loop (a.k.a., the Event Dispatch Thread or EDT) in response to various things happening such as mouse clicks, keyboard events, timers, ...
In an event driven program, "Wait until X" mostly means to disable something, and then re-enable it in the X handler.
Of course, Swing programs sometimes create other threads to handle input from sources that the GUI framework does not know about and, to perform "background" calculations. In that case, "Wait until X" might mean to signal some thread to pause, and then signal it to continue its work in the X handler.
I wrote a complex java program, that has a GUI.
In the GUI I have three buttons, "play", "play all" and "reset", and some table.
When I click play, the program does its logic and then prints the output to the table i mentioned. this is working fine, as intended. after a certain amount of "play" operations, we printed all the data to the table and so we are done and can no longer click it. at the point, i disable the play button.
When I click play all, I want it to be as if I clicked "play" until it is no longer possible. So I wrote this code:
public synchronized void actionPerformed(ActionEvent event)
{
if(event.getSource() == playAllButton)
{
while(playButton.isEnabled())
{
playButton.doClick();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if(event.getSource() == playButton)
{
Command command = listOfCommands.get(commandNumber++);
if(command.getCommandType() == "PF")
{
PFLabel.setText("PF Count:" + (++PFCount));
}
if(command.getCommandType() == "PR")
{
PRLabel.setText("PR Count:" + (++PRCount));
}
if(command.getCommandType() == "GP")
{
if(checkIfPF())
{
addPageToRam(((GPCommand)command).getPage());
}
else
{
if(checkIfPR(((GPCommand)command).getPage().getPageId()))
{
replacePage(((GPCommand)command).getPage(),getWithWhoToReplace(((GPCommand)command).getPage().getPageId()));
}
}
}
}
if(commandNumber == listOfCommands.size()) // we are done!
{
playButton.setEnabled(false);
}
}
As I mentioned, when I click the play button, it immediately prints the result as intended.
But when I click play all, it runs for a very long time without displaying any output, and then at the end prints just the final result. This isn't what I want. What I want is for it to print the current result, wait a bit so I can look at it, and then print the next result.
Even when I remove the Thread.sleep it is very slow (and still only prints the last result).
Is there a way to make it run faster? And more importantly - how do I make it wait before clicking the button again? I want to view the current result for a while before it clicks again.
In the comments section I figured out, that the issue could be solved by using SwingWorkers and moving the long-time-performing code to an asynchronous task. Mr. Coobird has posted a way, how to do this here.
Background: I am trying to programmatically create a context menu on an SWT Table. I am doing it programmatically because I need to hide/show the menu based on the cell that was clicked, not the row item.
I was planning to use the x,y coordinates from the Event class to find the cell that was clicked on, so I am capturing both the untyped MouseDown event and the untyped MenuDetect event. I put logging messages into the event handlers so I could better see what was going on. Here's my code:
tree.addListener(SWT.MouseDown, new Listener() {
#Override
public void handleEvent(final Event event) {
System.out.println("Mouse down: (" + event.x + ", " + event.y + ")");
handleMouseDown(event);
}
});
tree.addListener(SWT.MenuDetect, new Listener() {
#Override
public void handleEvent(final Event event) {
System.out.println("Menu Detect: (" + event.x + ", " + event.y + ")");
handleMenuDetect(event);
}
});
With the same click, I expected to see the same results, however, my output was as follows when I clicked down a column of cells:
Mouse down: (334, 11) Menu Detect: (1270, 255)
Mouse down: (331, 37) Menu Detect: (1267, 281)
Mouse down: (329, 55) Menu Detect: (1265, 299)
Mouse down: (324, 77) Menu Detect: (1260, 321)
Mouse down: (324, 100) Menu Detect: (1260, 344)
What is going on here? Aren't they referring to the same exact point? Are they calculating the x,y from different origins?
Are they calculating the x,y from different origins?
Yes, they do.
The SWT.MenuDetect event position is the mouse position based on the whole screen, whereas the SWT.MouseDown event position is based on its composite.
That means that one tells you where on the screen the event occurred, whereas the other tells you where in the widget it occurred.
To make them use the same coordinate system (the widget's system), call Control#toControl(int, int) to map it.
tree.addListener(SWT.MouseDown, (e) -> {
System.out.println(new Point(e.x, e.y));
});
tree.addListener(SWT.MenuDetect, (e) -> {
System.out.println(tree.toControl(e.x, e.y));
});
Control#toDisplay(int, int) will do the opposite.
For reference:
MouseEvent Javadoc:
public int x
the widget-relative, x coordinate of the pointer at the time the mouse button was pressed or released
MenuDetectEvent Javadoc:
public int x
The display-relative x coordinate of the pointer at the time the context menu trigger occurred.
I am using this code to get the X and Y coordinates of an image placed as icon of a jLable.
This method to get the coordinates was suggested by an answer to this question.
private void lblMapMouseClicked(java.awt.event.MouseEvent evt) {
lblMap.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
double X = e.getX();
double Y = e.getY();
System.out.println("X: " + X + "Y: " + Y );
}
});
}
When I run this public void mouseClicked(MouseEvent e) { } gets called multiple times.
Exactly the amount of times I click on the image.
Eg: If I'm clicking on it for the 3rd time ,
X and Y values from the System.out.println line , gets printed 3 times.
And it increases as the number of times I click increases.
Can any of you explain why this happens? And how can I fix it? :)
The problem is that you are adding a new listener again and again when click happens, here.
private void lblMapMouseClicked(MouseEvent evt)
{
lblMap.addMouseListener(new MouseAdapter()
{
...
Instead, change your code to this.
private void lblMapMouseClicked(MouseEvent e)
{
double X = e.getX();
double Y = e.getY();
System.out.println("X: " + X + "Y: " + Y);
}
And it should fix the problem.
Hope this helps.
it looks for me that every time image is clicked new mouse listener is added.. do also
System.out.println(this)
to check from which instance of mouse listener it is actually printed
The problem with above code was you are creating new Mouse event with every click on the image.
// Create a Mouse pressed Event
mouseLis = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
actionMenthod(e);
}
};
Here am attaching the my event to lblMap.
lblMap.addMouseListener(mouseLis);
After this event happens you have to remove this event from the lblmap.
lblMap.removeMouseListener(mouseLis);
After when I click again only one event will be there then it prints only once.
I'm working through the Stanford CS106A lectures and have hit a snag in the breakout project.
After I addMouseListeners(), I cannot detect mouseMoved calls.
However if I rename mouseMoved() to mouseDragged() or mouseClicked() or mousePressed() etc, it all updates correctly. Only the moved method does not work.
No errors or alerts, just doesn't detect the mouse being moved.
Any idea why that would happen?
public void run() {
/* Add a listener for the mouse */
addMouseListeners();
label = new GLabel("Mouse x & y");
add(label, 50, 50);
/* Load the method to create the brick pattern */
createBricks();
}
/** Detect a mouse move and update something */
public void mouseMoved(MouseEvent e){
label.setLabel("Mouse: " + e.getX() + " , " + e.getY());
paddle.setLocation(e.getX(), getHeight()-PADDLE_Y_OFFSET);
}
You need to use addMouseMotionListeners();. addMouseListeners is only for the functions that you were using.