I am writing a code that can take some boolean values from a part of some other code and change colours of certain circles on the screen accordingly. However I ran into problems trying to bind the boolean values to colours. I ended up with this:
unit1.getNeuron().getWorkingProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue == Boolean.FALSE) {
controller.paint1 = new ObservableValueBase<Paint>() {
#Override
public Paint getValue() {
return Color.RED;
}
};
} else {
controller.paint1 = new ObservableValueBase<Paint>() {
#Override
public Paint getValue() {
return Color.DODGERBLUE;
}
};
}
}
});
but I'll have to repeat it for n times for n variables I use. Is there a different way to implement this?
Let' s say you want to create an ObservableObjectValue<Paint> you want to toggle based on an ObservableBooleanValue, then Bindings is your friend:
final ObservableBooleanValue booleanCondition = unit1.getNeuron().getWorkingProperty();
final ObservableObjectValue<Paint> paintProperty = Bindings.when(booleanCondition).then(Color.RED).otherwise(Color.DODGERBLUE);
Related
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.
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 ?
I got a ScrollPane containing focusable Nodes.
The current default behaviour is:
Shift + ←, ↑, →, ↓ moves the focus
←, ↑, →, ↓ scrolls the view
I want it the other way around.
How can I accomplish this or where should I start?
[EDIT] Well, there is another fragile approach.
Instead of messing around with the events, one could mess around with the KeyBindings.
scrollPane.skinProperty().addListener(new ChangeListener<Skin<?>>() {
#Override
public void changed(ObservableValue<? extends Skin<?>> observable, Skin<?> oldValue, Skin<?> newValue) {
ScrollPaneSkin scrollPaneSkin = (ScrollPaneSkin) scrollPane.getSkin();
ScrollPaneBehavior scrollPaneBehavior = scrollPaneSkin.getBehavior();
try {
Field keyBindingsField = BehaviorBase.class.getDeclaredField("keyBindings");
keyBindingsField.setAccessible(true);
List<KeyBinding> keyBindings = (List<KeyBinding>) keyBindingsField.get(scrollPaneBehavior);
List<KeyBinding> newKeyBindings = new ArrayList<>();
for (KeyBinding keyBinding : keyBindings) {
KeyCode code = keyBinding.getCode();
newKeyBindings.add(code == KeyCode.LEFT || code == KeyCode.RIGHT || code == KeyCode.UP || code == KeyCode.DOWN ? keyBinding.shift() : keyBinding);
}
keyBindingsField.set(scrollPaneBehavior, newKeyBindings);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
LOGGER.warn("private api changed.", e);
}
}
});
I think, that could be the cleaner way, if KeyBindings were more non-static, modifyable and public.
Use an event filter to capture the relevant key events and remap them to different key events before the events start to bubble.
Re-mapping default keys is a tricky thing which:
Can confuse the user.
May have unexpected side effects (e.g. TextFields may no longer work as you expect).
So use with care:
import javafx.application.*;
import javafx.event.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;
import java.util.*;
public class ScrollInterceptor extends Application {
#Override
public void start(Stage stage) {
ScrollPane scrollPane = new ScrollPane(
createScrollableContent()
);
Scene scene = new Scene(
scrollPane,
300, 200
);
remapArrowKeys(scrollPane);
stage.setScene(scene);
stage.show();
hackToScrollToTopLeftCorner(scrollPane);
}
private void remapArrowKeys(ScrollPane scrollPane) {
List<KeyEvent> mappedEvents = new ArrayList<>();
scrollPane.addEventFilter(KeyEvent.ANY, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (mappedEvents.remove(event))
return;
switch (event.getCode()) {
case UP:
case DOWN:
case LEFT:
case RIGHT:
KeyEvent newEvent = remap(event);
mappedEvents.add(newEvent);
event.consume();
Event.fireEvent(event.getTarget(), newEvent);
}
}
private KeyEvent remap(KeyEvent event) {
KeyEvent newEvent = new KeyEvent(
event.getEventType(),
event.getCharacter(),
event.getText(),
event.getCode(),
!event.isShiftDown(),
event.isControlDown(),
event.isAltDown(),
event.isMetaDown()
);
return newEvent.copyFor(event.getSource(), event.getTarget());
}
});
}
private TilePane createScrollableContent() {
TilePane tiles = new TilePane();
tiles.setPrefColumns(10);
tiles.setHgap(5);
tiles.setVgap(5);
for (int i = 0; i < 100; i++) {
Button button = new Button(i + "");
button.setMaxWidth(Double.MAX_VALUE);
button.setMaxHeight(Double.MAX_VALUE);
tiles.getChildren().add(button);
}
return tiles;
}
private void hackToScrollToTopLeftCorner(final ScrollPane scrollPane) {
Platform.runLater(new Runnable() {
#Override
public void run() {
scrollPane.setHvalue(scrollPane.getHmin());
scrollPane.setVvalue(0);
}
});
}
public static void main(String[] args) {
launch(args);
}
}
In swing is a FocusManager available to get notified if the focus changes.
FocusManager.getCurrentManager().addPropertyChangeListener (...)
Is there an analogue way in javafx to get notified if the focus in the scenegraph changes?
You can add a ChangeListener to the focusOwner property of a Scene now:
scene.focusOwnerProperty().addChangeListener(...)
There's none yet but you can try manually looping among the focusedProperties of your target nodes
private void handleFocusChangesStartingFromParentNode(Parent parentNode) {
for (Node node : parentNode.getChildrenUnmodifiable()) {
node.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
performHandling();
}
});
try{
handleFocusChangesStartingFromNode((Parent)node);
}catch(ClassCastException e){
}
}
}
I'm rolling my own ActivatableCollection<T> for db4o but cribbing heavily from the builtin ActivatableList<T> implementation. I'm running into the problem where transparent persistence doesn't seem to be working correctly. In the test code below:
[Fact]
void CanStoreActivatableCollection()
{
var planets = new ActivatableCollection<Planet>();
var pagingMemoryStorage = new PagingMemoryStorage();
var config = Db4oEmbedded.NewConfiguration();
config.Common.Add(new TransparentActivationSupport());
config.Common.Add(new TransparentPersistenceSupport());
config.File.Storage = pagingMemoryStorage;
var objectContainer = Db4oEmbedded.OpenFile(config, "Memory.yap");
planets.Add(new Planet("Mercury"));
objectContainer.Store(planets);
planets.Add(new Planet("Venus"));
planets.Add(new Planet("Earth"));
objectContainer.Commit();
objectContainer.Close();
config = Db4oEmbedded.NewConfiguration();
config.Common.Add(new TransparentActivationSupport());
config.Common.Add(new TransparentPersistenceSupport());
config.File.Storage = pagingMemoryStorage;
objectContainer = Db4oEmbedded.OpenFile(config, "Memory.yap");
planets = objectContainer.Query<ActivatableCollection<Planet>>().FirstOrDefault();
Assert.NotNull(planets);
Assert.Equal(3, planets.Count);
objectContainer.Close();
}
The planet "Mercury" is stored, but not "Venus" and "Earth". If I change from ActivatableCollection to ActivatableList, then all 3 planets are stored.
What am I missing? My ActivatableCollection is just minimal implementation of ActivatableList as best as I can tell.
Below is my implementation of ActivatableCollection:
public class ActivatableCollection<T>
: ICollection<T>
, IActivatable
, INotifyCollectionChanged
{
List<T> _list;
List<T> List
{
get
{
if (_list == null)
_list = new List<T>();
return _list;
}
}
public ActivatableCollection()
{
}
public int Count
{
get
{
ActivateForRead();
return List.Count;
}
}
public bool IsReadOnly
{
get
{
ActivateForRead();
return ((IList) List).IsReadOnly;
}
}
public void Add(T t)
{
ActivateForWrite();
List.Add(t);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, t));
}
public void Clear()
{
ActivateForWrite();
List.Clear();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
public bool Contains(T t)
{
ActivateForRead();
return List.Contains(t);
}
public void CopyTo(T[] array, int index)
{
ActivateForRead();
List.CopyTo(array, index);
}
public IEnumerator<T> GetEnumerator()
{
ActivateForRead();
return List.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool Remove(T t)
{
ActivateForWrite();
bool removed = List.Remove(t);
if (removed)
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, t));
return removed;
}
[Transient]
private IActivator _activator;
public virtual void Bind(IActivator activator)
{
if (_activator == activator)
return;
if (activator != null && _activator != null)
throw new InvalidOperationException();
_activator = activator;
}
public virtual void Activate(ActivationPurpose purpose)
{
if (_activator == null)
return;
_activator.Activate(purpose);
}
protected virtual void ActivateForRead()
{
Activate(ActivationPurpose.Read);
}
protected virtual void ActivateForWrite()
{
Activate(ActivationPurpose.Write);
}
[Transient]
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
CollectionChanged(this, e);
}
}
I've also tried copying the code from GenericTypeHandlerPredicate and registering my ActivatableCollection to use the GenericCollectionTypeHandler. That results in a crash in GenericTypeFor() throwing an InvalidOperationException() when "Mercury" is being stored.
Just want to mention my answers from the db4o forums also here, for people with a similar problem:
First part of the issue:
From db4o's point of view nothing has changed in the 'ActivatableCollection' object and therefore no changes are stored. This is what is happening:
When you add the items, the ActivatableCollection is marked as changed.
When you commit the changes are stored. However the ' ActivatableCollection' holds the reference to the same object. db4o only stores the changes in the ActivatableCollection-object, which is the reference to the List. Since it is the same, no actual change is stored.
The List of the ActivatableCollection is never updated, because it wasn't marked as 'changed'
So the transparent activation doesn't see the changes in the list. You can fix your issue simply by using an ActivatableList in you're ActivatableCollection implementation. Just change the List with a IList interface and instantiate a ActivatableList instead of an List.
The second part of the issue: Why doesn't it work even when registering the GenericCollectionTypeHandler for this type? Here we hit a implementation detail. The GenericCollectionTypeHandler has an internal list of supported types, which doesn't include the self made 'ActivatableCollection'. GenericCollectionTypeHandler is not really part of the public API and intendet for internal use only.
Workaround / Fix
Just use an ActivatableList<T> instead of a List<T>. then everything works fine.