Mimicking jQuery event.which in GWT - java

The GwtQuery documentation provides the following example as a starting point for fiddling with events:
$("h1").bind(Event.ONMOUSEOVER | Event.ONMOUSEOUT, new Function() {
public boolean f(Event e) {
$(e).toggleClass("highlight");
return true;
}
});
However, unlike the jQuery parallel, there is no this keyword to refer to the element inside the handler, that's why it is passed as Event e, to be wrapped within $(). But then, we don't have access to the actual event. How do we calculate in GWT what we can in jQuery with event.which, or event.target?
Specifically, I am looking for two events. One is a mousedown, after which I need to check whether it was the left button (jQuery equivalent being e.which == 1), and a keyup event, after which I need to check for specific keys (e.keyCode == 13, etc).

The Event object passed to the function is the GWT object com.google.gwt.user.client.Event
So if you want to know if the left button was pressed :
if (e.getButton() == NativeEvent.BUTTON_LEFT){
...
}
if you want to know which key was pressed:
e.getCharCode()

Related

How would I refactor repetitive code?

Apologies for the poor title, but I can't really think of an informative title for this.
I'll be straight forward here:
setName(); // set the name field
validate(); // submit the form and check if form has error
setName();
setAge();
validate();
setName();
setAge();
setHeight();
validate();
setName();
setAge();
setHeight();
setGender();
validate();
// the list goes on...
I am testing a form on a website and the form should not allow any empty fields, however upon a submit button click any fields that I've entered in before gets cleared, which is why I need to set the previous fields all over again like the above code.
What would be a more elegant way to write this? I was thinking of a loop but then I could not think of the right conditions...
You can create a Runnable instance for each of the actions and put them in a list.
In Java 8+:
List<Runnable> runnables = new ArrayList<>();
runnables.add(() -> setName());
runnables.add(() -> setAge());
runnables.add(() -> setHeight());
// ... etc
For earlier versions of Java, you can use anonymous classes:
runnables.add(new Runnable() { #Override public void run() { setName(); } });
// ... etc
and then execute the Runnable instances in a sublist of runnables:
for (int i = 0; i < runnables.size(); ++i) {
for (Runnable fn : runnables.subList(0, i + 1)) {
fn.run();
}
validate();
}
Demo
I'm unsure as to whether I fully understand your question (perhaps a pastebin as to a working example would help), however perhaps you could have a boolean for each field that checks as to whether the field has been modified since the last check, and then you set field based on the state of these booleans?
The checking method would then reset all booleans to false (or whatever method actually submits the changes).

How to stop object from moving while key is still pressed

I'm a beginner in Java programming & I am making an application requiring an object to move around a grid filled with squares.
The object should only move one square at a time and if the user wants to move into another square, they must press the key again. My move method is the following:
public void move() {
x += dx;
y += dy;
}
I am using the KeyListener interface to implement the keyPressed, keyTyped and keyReleased methods and I have conditions like the one in the fragment below inside KeyPressed
//KeyPressed
int c = e.getKeyCode();
if (c == KeyEvent.VK_UP) {
player.setDy(-5);
}
This allows the object to move freely. However, it will clearly continue to move as long as the UP arrow is pressed.
Is there any way to have to object move up by say -5 once and then stop even if the key is still pressed?
I am unsure whether I need to change my move method or the KeyListener methods to do this.
I hope that I have been clear enough as to what I'm asking and I'd highly appreciate any pointers.
first of all : you should use Synchronization if you call class-methods from within listeners like keyPressed or keyReleased - thats because your listener-method can be called from multiple threads so your class-method (player.setDy()) can (and will) be called in parallel - you will need to make sure that each call to setDy happens before the next one.
Also : keyTyped is much better in many cases : https://stackoverflow.com/a/7071810/351861
An example could look like this:
public void keyTyped(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_UP)
{
synchronized(player)
{
player.setDy(-5);
}
}
}
this will call setDy sequentially and reliably. Now all you need to do is to make sure that setDy works as intended, hence sets the position only once
easiest would be to add a boolean to indicate, that a moving key is pressed
class member : boolean movingKeyPressed = false
in key pressed :
if (movingKeyPressed) {
return;
} else {
// do stuff
movingKeyPressed = true;
}
in key released method :
movingKeyPressed = false;

Java/JavaFX2: dynamic GUI, detect which button was pressed, extract id

I'm a newbie in Java/JavaFX (I began yesterday evening). I'm building a dynamic GUI (crud) reading off a MySQL database.
I managed to display the data in a table and add a button next to each row.
Since the number of buttons is variable, I want to define only a common eventhandler.
The problem is that whenever I use event.getSource() (it's an ActionEvent) and display it, I get something like "Button[id=0, styleClass=button].
Question 1: Is there any way I could put the id in a variable? I can't get it out of the object.
As far as I know, I have to use the id, since I can't do something like this "if(event.getSource() == somebutton) {...}" since every generated button had the same variable name.
Now, this is the loop (inside a method called make_buttons) that builds the buttons. n_buttons is the number of buttons I want to build.
for(int counter = 0; counter < n_buttons; counter++){
String newtext = new String("btn"+counter);
Button btn = new Button();
btn.setText(newtext);
btn.setId(Integer.toString(counter));
btn.setOnAction(myHandler);
grid.add(btn,0,counter);
}
Note that I'm placing the buttons on a gridpane one on top of the other.
Before that part I have my handler:
final EventHandler<ActionEvent> myHandler = new EventHandler<ActionEvent>(){
public void handle(final ActionEvent event) {
Object new_output = event.getSource();
System.out.println(new_output);
event.consume();
}
};
Question 2: so, how can I differentiate which button fired the event in my particular case?
I know quite a few programming languages (Matlab, R, Python, C, Assembly, etc... but I'm a hobbyist), but it's the first time I'm working with GUI elements (except web languages and ActionScript 3).
In actionscript I could just do something like event.getCurrentTarget and the use it exactly as if it were the object itself to read the id, properties, etc.
I looked everywhere and couldn't find anything (maybe my terminology was a bit approximative...).
If I understand your question correcty, you can simply access the clicked button in you handle method with the following code:
Object source = event.getSource();
if (source instanceof Button) { //should always be true in your example
Button clickedBtn = (Button) source; // that's the button that was clicked
System.out.println(clickedBtn.getId()); // prints the id of the button
}

Key Bindings Fire Multiple Times when Holding Key

I'm following this guide to get key binding to work in my application. So far, the key bindings fire successfully, when I press a key. What I expect to happen is when I bind one action to a key pressed event and another action to a key released event, it will fire the first action when the key is pressed down and the second action when the key is released. What actually happens when I hold down a key is both actions get called multiple times. What can I do to achieve my desired behavior?
Here's how I'm implementing the key bindings:
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("pressed UP"), "pressedUP");
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released UP"), "releasedUP");
Action pressedUpAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Pressed UP");
}
};
Action releasedUpAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Released UP");
}
};
component.getActionMap().put("pressedUP", pressedUpAction);
component.getActionMap().put("releasedUP", releasedUpAction);
When I run the program, the output I actually get when I hold down the up key is Pressed UP, a slight pause, and then multiple Pressed UP values. When I release the up key, I get a Released UP message. The entire output looks like this:
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Pressed UP
Released UP
The really weird thing is if I replace UP with a keyboard letter key, such as P, everything works as I expect it to.
use Boolean value inside Swing Action when once times fired events then change Boolean from false to true or vice versa
I'm sorry nobody knows how did you implemented KeyBindings, post an SSCCE

Which button of JSpinner has been pressed?

Is it possible to know , from inside a ChangeListener receiving a ChangeEvent from a JSpinner,
which button (increment/decrement) has been pressed?
Short answer : No there's no way to know which button was pressed
Long answer : depending on your model and your change listener, if you do a comparison between the new value and the previous value, it is possible to know if the user went forward or backward.
You can inspect the object firing the event. Perhaps save the value prior to the event and determine whether it went up or down during the event.
Compare the actual value to the previous one. Here is how:
ChangeEvent ce = ...
((JSpinner)ce.getSource()).getPreviousValue();
You can check the new value against the old value by storing the old value:
int currentValue = spinner.getValue();
spinner.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent e) {
int value = spinner.getValue();
if(value > currentValue) {
// up was pressed
} else if(value < currentValue) {
// down was pressed
}
currentValue = value;
}
});
JSpinner is a composite component, it's possible to add mouseListeners to the components it contains. You'd have to experiment a bit to work out how to distinguish the buttons from one another and from the text field. One quick and dirty way would be to check their coordinates.
I'm not sure if you want to iterate over the components contained by the JSpinner itself, or those contained by the container returned by JSpinner.getEditor(), so try both.

Categories