Vaadin: MouseDown/MouseUp and KeyDown/KeyUp evens - vaadin

Is it possible to handle MouseDown/MouseUp and KeyDown/KeyUp evens with Vaadin? I've found forum thread with the same question and looks like the answer is no, but it was 5 years ago - I hope something changed with later releases. Still I can't find anything in API. Maybe there's some workaround for intercepting such evens?

Well, after couple of days I came up with the acceptable (for me) solution. Required component has to be wrapped with extension-interceptor (credits to #petey for an idea in the comments) with KeyDownHandler inside. But the trick is not to add to the component itself (because it can miss triggering), but to the RootPanel. So here's a working example.
Extension:
public class InterceptorExtension extends AbstractExtension {
private boolean shiftKeyDown;
public InterceptorExtension(Tree tree) {
super.extend(tree);
registerRpc((InterceptorExtensionServerRpc) state -> shiftKeyDown = state);
}
public boolean isShiftKeyDown() {
return shiftKeyDown;
}
}
ServerRpc:
public interface InterceptorExtensionServerRpc extends ServerRpc {
void setShiftKeyDown(boolean state);
}
Connector:
#Connect(InterceptorExtension.class)
public class InterceptorExtensionConnector extends AbstractExtensionConnector {
#Override
protected void extend(final ServerConnector target) {
final InterceptorExtensionServerRpc rpcProxy = getRpcProxy(InterceptorTreeExtensionServerRpc.class);
final RootPanel rootPanel = RootPanel.get();
rootPanel.addDomHandler(new KeyDownHandler() {
#Override
public void onKeyDown(KeyDownEvent event) {
if (event.isShiftKeyDown()) {
rpcProxy.setShiftKeyDown(true);
}
}
}, KeyDownEvent.getType());
rootPanel.addDomHandler(new KeyUpHandler() {
#Override
public void onKeyUp(KeyUpEvent event) {
if (!event.isShiftKeyDown()) {
rpcProxy.setShiftKeyDown(false);
}
}
}, KeyUpEvent.getType());
}
}
Then whenever you want you can get Shift-button state on the server-side via InterceptorExtension#isShiftKeyDown.

Related

Vaadin Grid middle mouse click

I'm trying to emulate normal browser behaviour in my vaadin grid, which includes middle mouse click to open in a new tab:
addItemClickListener(e -> {
boolean newTab = e.getMouseEventDetails().getButton() == MouseEventDetails.MouseButton.MIDDLE || e.getMouseEventDetails().isCtrlKey();
//open in window or new tab
});
However, the middle mouse button is not registered by vaadin. How could I get this to work?
That feature was included in vaadin-grid (which goes into Vaadin 10) and will not work in Vaadin 8.
For Vaadin 8, you can either intercept the event with some client-side extension, or use a ComponentRenderer for adding a Panel to each component (which works, but is not ideal because it degrades performance):
grid.addColumn(item->{
Panel p = new Panel(item.getName());
p.setStyleName(ValoTheme.PANEL_BORDERLESS);
p.addClickListener(ev->{
System.out.println(ev.getButtonName());
});
return p;
}).setRenderer(new ComponentRenderer());
A client-side extension, on the other hand, allows listening to javascript events (such as MouseEvent) and triggering a server event in response. Creating a extension is quite a complex topic (since it uses a part of the API that is normally hidden from the developer) but it allows direct access to rendered DOM, which is not possible otherwise.
The following resources from the documentation may give you a starting point:
Creating a component extension (which describes a simple extension with Java code only) and Integrating JavaScript Components and Extension (which explains how to add native JavaScript code to your extension).
How I solved the problem in my specific case:
Server side:
public class MyGrid<T> extends Grid<T> {
public MyGrid(String caption, DataProvider<T, ?> dataProvider) {
super(caption, dataProvider);
MiddleClickExtension.extend(this);
}
public static class MiddleClickExtension<T> extends AbstractGridExtension<T> {
private MiddleClickExtension(MyGrid<T> grid) {
super.extend(grid);
registerRpc((rowKey, columnInternalId, details) -> grid.fireEvent(
new ItemClick<>(grid, grid.getColumnByInternalId(columnInternalId), grid.getDataCommunicator().getKeyMapper().get(rowKey), details)),
MiddleClickGridExtensionConnector.Rpc.class);
}
public static void extend(MyGrid<?> grid) {
new MiddleClickExtension<>(grid);
}
#Override
public void generateData(Object item, JsonObject jsonObject) {
}
#Override
public void destroyData(Object item) {
}
#Override
public void destroyAllData() {
}
#Override
public void refreshData(Object item) {
}
}
}
Client side:
#Connect(MyGrid.MiddleClickExtension.class)
public class MiddleClickGridExtensionConnector extends AbstractExtensionConnector {
#Override
protected void extend(ServerConnector target) {
getParent().getWidget().addDomHandler(event -> {
if (event.getNativeButton() == NativeEvent.BUTTON_MIDDLE) {
event.preventDefault();
CellReference<JsonObject> cell = getParent().getWidget().getEventCell();
getRpcProxy(Rpc.class).middleClick(cell.getRow().getString(DataCommunicatorConstants.KEY), getParent().getColumnId(cell.getColumn()),
MouseEventDetailsBuilder.buildMouseEventDetails(event.getNativeEvent(), event.getRelativeElement()));
}
}, MouseDownEvent.getType());
}
#Override
public GridConnector getParent() {
return (GridConnector) super.getParent();
}
public interface Rpc extends ServerRpc {
void middleClick(String rowKey, String columnInternalId, MouseEventDetails details);
}
}

Binding between an Object and a SimpleIntegerProperty

I have a combo box over my GUI in JavaFX.
This Combo Box is composed of a complex type elements :
public class DureeChoiceBoxElement extends ObservableValueBase<DureeChoiceBoxElement> {
private IntegerProperty duree;
#Override
public String toString() {
return duree.get() + " an";
}
}
I want to map (or bind) the selected complex element with my model which contains the simple type :
public class Pel {
private IntegerProperty duree = new SimpleIntegerProperty(1);
public Property<Number> dureeProperty() {
return duree;
}
public void setDuree(Integer duree) {
this.duree.setValue(duree);
}
public Integer getDuree() {
return duree.getValue();
}
}
How to do it ?
I tried in the controller with :
public class PelController {
#FXML
private ChoiceBox<DureeChoiceBoxElement> duree;
//etc..
pel.dureeProperty().bind(createElapsedBindingByBindingsAPI2(duree.getValue()));
/*
* #return an ObjectBinding of immutable TimeElapsed objects for the player
*/
private ObjectBinding<Property<Number>> createElapsedBindingByBindingsAPI2(
final DureeChoiceBoxElement dureeChoiceBoxElement) {
return Bindings.createObjectBinding(new Callable<Property<Number>>() {
#Override
public IntegerProperty call() throws Exception {
return dureeChoiceBoxElement.dureeProperty();
}
}, dureeChoiceBoxElement.dureeProperty());
}
}
But it doesn't work (even not compile). I want to say that "Bind this simple property to this complex Object calling the method I give you through the method named "createElapsedBindingByBindingsAPI2(..)".
It is logical read but I didn't managed to make it works anyway.
That's poor ....
Any help please :).
Example that (obviously) works with legacy code style (Swing coding) :
duree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<DureeChoiceBoxElement>() {
#Override
public void changed(ObservableValue<? extends DureeChoiceBoxElement> observable,
DureeChoiceBoxElement oldValue, DureeChoiceBoxElement newValue) {
// changement durée
log.debug("Durée sélectionnée : {}", duree.getSelectionModel().getSelectedItem().getDuree());
log.debug("Durée bindée ? : {}", pel.getDuree());
pel.setDuree(duree.getSelectionModel().getSelectedItem().getDuree());
}
});
Like this my model is set to selected item. But it implies some boilerplate code. Any better idea based on high level bindings of JavaFX ?

NullPointerException when overiding the ConnectorTracker.getConnectorTracker

After reading this article Vaadin "A connector with id xy is already registered", I've try to implement the solution suggested by Jose Luis...
But I get this traces :
java.lang.NullPointerException
at com.vaadin.server.AbstractClientConnector.markAsDirty(AbstractClientConnector.java:138)
at com.vaadin.ui.AbstractComponent.setWidth(AbstractComponent.java:844)
at com.vaadin.ui.AbstractSingleComponentContainer.setWidth(AbstractSingleComponentContainer.java:210)
at com.vaadin.ui.AbstractComponent.setSizeFull(AbstractComponent.java:817)
at com.vaadin.ui.UI.<init>(UI.java:253)
at com.vaadin.ui.UI.<init>(UI.java:238)
at my.package.ui.MyUI.<init>(MyUI.java:72)
where line 72 corresponding to :
public class MyUI extends UI
Could someone can help to understand why these traces ?
I could provide more code if necessary.
Information :
public class MyUI extends UI {
private final MyConnectorTracker tracker = new MyConnectorTracker(
this);
#Override
public ConnectorTracker getConnectorTracker() {
return this.tracker;
}
}
public class MyUI extends UI {
private MyConnectorTracker tracker;
#Override
public ConnectorTracker getConnectorTracker() {
if (this.tracker == null) {
this.tracker = new MyConnectorTracker(this);
}
return this.tracker;
}
}
This resolve the NullPointerException. It is too early to set tracker on the first call of UI.

AndroidAnnotations in CursorAdapter

I am developing for android using android annotations but I don't unterstand how to use it with CursorAdapters.
There is already a example for BaseAdapters, but if I add #EBean to a class that extents CursorAdapter I get the error message "#EBean annotated element should have a constructor with one parameter max, of type android.content.Context". CursorAdapter already has two constructors.
public class SongInfoAdapter extends CursorAdapter {
...
#Override
public void bindView(View view, Context context, Cursor cursor) {
...
rowData.id.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
itemOnClick(rowData);
}
});
}
public void itemOnClick(RowDataHolder rowData) {
switch(audioPlayer.getPlayingplayer()) {
case AudioPlayer.RIGHT:
case AudioPlayer.NONE:
audioPlayer.load(rowData.songInfo, AudioPlayer.LEFT);
break;
case AudioPlayer.LEFT:
audioPlayer.load(rowData.songInfo, AudioPlayer.RIGHT);
break;
}
}
...
}
AudioPlayer is a class that uses annotations (#EBean), but I can't write
#Bean
AudioPlayer audioPlayer;
because I can't use annotations in this class. How can I use AndroidAnnotations in CursorAdapter?
Many thanks in advance .
Create a constructor that takes one argument, the context.
SongInfoAdapter (Context context) {
super(context, null, FLAG_AUTO_REQUERY);
}
Create an init method and set the cursor for the adapter in init.
public void init(Cursor c) {
this.changeCursor(c);
}
Now you can annotate SongInfoAdapter with #EBean and use annotations.

I ported my midlet to Blackberry and I can't assign a listener to the ESCAPE key

Here is some of the code in my midlet:
the addKeyListener method presents an error as the function is not recognized.
import net.rim.device.api.system.KeyListener;
import net.rim.device.api.ui.Keypad;
public class PhraZApp extends javax.microedition.midlet.MIDlet implements ActionListener{
public PhraZApp {
addKeyListener (new KeyPadListener());
}
protected void keyPressed(int key) {
System.out.println(key);
}
public void actionPerformed(ActionEvent evt) {
System.out.println(evt.getKeyEvent());
}
public final class KeyPadListener implements KeyListener {
public boolean keyChar(char key, int status, int time) {
return false;
}
public boolean keyDown(int keycode, int time) {
if (Keypad.KEY_ESCAPE == Keypad.key(keycode)) {
System.out.println("key: " + keycode);
return true;
}
//let the system to pass the event to another listener.
return false;
}
public boolean keyUp(int keycode, int time) {
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean keyRepeat(int keycode, int time) {
throw new UnsupportedOperationException("Not supported yet.");
}
public boolean keyStatus(int keycode, int time) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
The keyPressed action is not heard by any of those listeners.
Ive been told to add the keylistner to a GUI component, but none that I try it with accept it.
Furthermore, one of the possible issues is that the addKeyListener method is not declared, but in that case I don't know how to declare it.
If i change extends javax.microedition.midlet.MIDlet to extends UiApplication, the addKeyListener becomes accepted but the entire midlet falls to a RuntimeErrorException.
How can I get my Midlet to hear the escape key? I have searched through many forums and none of the suggestions have worked so far.
Thanks in advance.
You need to create a LWUIT Command and assign it to the parent form using the setBackCommand method. You can handle the command event like you handle every other command in LWUIT. E.g. through a command listener or even just by subclassing it and overriding actionPerformed(ActionEvent).
Thanks to Shai pointing me in the right direction, I solved it.
Here is how I did it.
Command backCommand = new Command("",Keypad.KEY_ESCAPE);
form.setBackCommand(backCommand);
then
public void actionPerformed(ActionEvent evt) {
if (evt.getCommand().getId() ==Keypad.KEY_ESCAPE){
//execution code
}
I didn't try, but if I had included text in the command I imagine it would appear as such when I push the menu button. The important thing is that I finally got the MIDlet to hear out the escape button after MANY hours of trying and searching for solutions.

Resources