Custom context menu on custom TreeItems - treeview

My domain model consists of multiple types of objects that need to be listed in a tree view, let's call them A and B. Each of these types needs to do a different action when selected in the tree view.
What I have done is this:
Created an interface for both of them to implement:
public interface ITVItem
{
public String toString();
public void HandleClick();
}
public class A implements ITVItem
{
#Override
public void HandleClick()
{
//Do something
}
#Override
public String toString()
{
return "Item type A";
}
}
public class B implements ITVItem
{
#Override
public void HandleClick()
{
//Do something different
}
#Override
public String toString()
{
return "Item type B";
}
}
The tree view is populated like this:
TreeItem<ITVItem> tvItem= new TreeItem<ITVItem> (new A());
rootNode.getChildren().add(target);
treeView.setRoot(rootNode);
Now, when the user clicks on an item i handle it like this:
#FXML
private void SelectionChanged(MouseEvent event)
{
Node node = event.getPickResult().getIntersectedNode();
// Accept clicks only on node cells, and not on empty spaces of the TreeView
if (node instanceof Text || (node instanceof TreeCell && ((TreeCell) node).getText() != null))
{
tVMain.getSelectionModel().getSelectedItem());
ITVItem tvItem = ((ITVItem) ((TreeItem) tVMain.getSelectionModel().getSelectedItem()).getValue());
tvItem.HandleClick();
}
}
What I need next is to have a custom context menu for each of the domain object types (A and B) to appear when the user right-clicks. How am I supposed to do this?

Related

Toast is shown every time when device is rotate

In my Android app I use AAC.
Here my activity:
public class AddTraderActivity extends AppCompatActivity {
AddTraderViewModel addTraderViewModel;
private static final String TAG = AddTraderActivity.class.getName();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AddTraderActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.add_trader_activity);
binding.setHandler(this);
init();
}
private void init() {
ViewModelProvider viewViewModelProvider = ViewModelProviders.of(this);
addTraderViewModel = viewViewModelProvider.get(AddTraderViewModel.class);
Observer<String> () {
#Override
public void onChanged (String message){
Debug.d(TAG, "onChanged: message = " + message);
Toast.makeText(AddTraderActivity.this, message, Toast.LENGTH_LONG).show();
}
});
}
public void onClickStart() {
EditText baseEditText = findViewById(R.id.baseEditText);
EditText quoteEditText = findViewById(R.id.quoteEditText);
addTraderViewModel.doClickStart(baseEditText.getText().toString(), quoteEditText.getText().toString());
}
}
Here my ViewModel:
public class AddTraderViewModel extends AndroidViewModel {
private MutableLiveData<String> messageLiveData = new MutableLiveData<>();
private static final String TAG = AddTraderViewModel.class.getName();
public AddTraderViewModel(#NonNull Application application) {
super(application);
}
public void doClickStart(String base, String quote) {
Debug.d(TAG, "doClickStart: ");
if (base.trim().isEmpty() || quote.trim().isEmpty()) {
String message = getApplication().getApplicationContext().getString(R.string.please_input_all_fields);
messageLiveData.setValue(message);
return;
}
}
public LiveData<String> getMessageLiveData() {
return messageLiveData;
}
}
So when I click on button on Activity call method onClickStart()
If any fields is empty the show toast. In the activity call method:
onChanged (String message)
Nice. It's work fine.
But the problem is, when I rotate the device in the activity method onChanged(String message) is called AGAIN and as result show toast. This happened on every rotation.
Why?
This is the expected behaviour. If you want to avoid this you must set message = "" and keep an empty check before showing the toast.
A better way to use it is something like Event Wrapper or SingleLiveEvent
Highly recommend you to read this article. This explains why you are facing this and what are your options in detail.

Chain CollectionChanged Events

I'm trying to see how it would be possible to chain together x number of ObservableCollections.CollectionChanged event, exposed as a N level depth object tree to a single parent level CollectionChanged event that consumers can listen to? Essentially I want to funnel or bubble all child CollectionChanged events up to the top most parent. A number of solution I've noticed that tackle similar issues make an assumption of a fixed number of levels, say 2 deep. I idea is to support any level of depth.
Originally I had hoped I could just pass the instance of the FieldInfos to the child constructors and attach directly to the handler. However i get an error stating the "Event 'CollectionChanged' can only appear on the left hand side of+= or -=.
Thanks,
public class FieldInfos
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
private ObservableCollection<Field> _fields;
public ObservableCollection<Field> Fields => _fields ?? (_fields = new ObservableCollection<Field>());
}
public class Field
{
public string Name;
private ObservableCollection<FieldInstance> _instances;
public ObservableCollection<FieldInstance> Instances => _instances ?? (_instances = new ObservableCollection<FieldInstance>());
}
public class FieldInstance
{
public string Id { get; set; }
}
The simplest approach is subclass the original ObservableCollection<T>.
You'd need at least one interface to avoid covariance problems. You can also have your own classes to implement the INotifyDescendantsChanged interface.
public interface INotifyDescendantsChanged
{
event NotifyCollectionChangedEventHandler DescendantsChanged;
}
public class ObservableBubbleCollection<T> : ObservableCollection<T>, INotifyDescendantsChanged
{
public event NotifyCollectionChangedEventHandler DescendantsChanged;
protected virtual void OnDescendantsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
NotifyCollectionChangedEventHandler handler = DescendantsChanged;
if (handler != null)
handler(sender, e);
}
private readonly Func<T, INotifyDescendantsChanged> childSelector;
public ObservableBubbleCollection() { }
public ObservableBubbleCollection(Func<T, INotifyDescendantsChanged> childSelector)
{
this.childSelector = childSelector;
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);
OnDescendantsChanged(this, e);
if (childSelector == null)
return;
if (e.NewItems != null)
foreach (var item in e.NewItems.Cast<T>())
childSelector(item).DescendantsChanged += OnDescendantsChanged;
if (e.OldItems != null)
foreach (var item in e.OldItems.Cast<T>())
childSelector(item).DescendantsChanged -= OnDescendantsChanged;
}
}
To use it, replace instances of ObservableCollection and pass a selector to the collection.
public class FieldInfos
{
private ObservableBubbleCollection<Field> _fields;
public ObservableBubbleCollection<Field> Fields => _fields ?? (_fields = new ObservableBubbleCollection<Field>(fi => fi.Instances));
}
public class Field
{
public string Name;
private ObservableBubbleCollection<FieldInstance> _instances;
public ObservableBubbleCollection<FieldInstance> Instances => _instances ?? (_instances = new ObservableBubbleCollection<FieldInstance>());
}
public class FieldInstance
{
public string Id { get; set; }
}
static class Program
{
static void Main(string[] args)
{
var fi = new FieldInfos();
fi.Fields.DescendantsChanged += (sender, e) =>
{
Console.WriteLine("Change from {0}", sender.GetType());
};
var field = new Field();
fi.Fields.Add(field);
field.Instances.Add(new FieldInstance());
Console.ReadLine();
}
}

Javafx: How to add eventhandlers to another seperate class

I have two buttons within in a pane on the scene. I have added the event handler like this:
Button reset=new Button ("Reset");
reset.addEventHandler(MouseEvent.MOUSE_CLICKED,new EventHandler<MouseEvent>(){
public void handle(MouseEvent event){
System.out.println("reseting");
model.reset();
Play(stage);
}});
Button guess=new Button ("Guess");
guess.addEventHandler(MouseEvent.MOUSE_CLICKED,new EventHandler<MouseEvent>(){
public void handle(MouseEvent event){
ArrayList<Integer> FullGuess=new ArrayList<Integer>();
boolean condition=true;
for (int y:fullGuess){
if (y==0){
condition=false;
}
}
}});
How can I do the event handling part in another class rather than doing it directly in the class as I have done?
Your fragment uses an anonymous class to handle events, but you can promote your anonymous handler to a member of the enclosing class or a separate class having package-private access. In either case, you'll want to pass the required List<Integer> as a parameter.
List<Integer> fullGuess = new ArrayList<Integer>();
…
Button guess = new Button("Guess");
guess.addEventHandler(MouseEvent.MOUSE_CLICKED, new MyEventHandler(fullGuess));
In another file:
class MyEventHandler implements EventHandler<MouseEvent> {
private final List<Integer> fullGuess;
public MyEventHandler(List<Integer> fullGuess) {
this.fullGuess = fullGuess;
}
#Override
public void handle(MouseEvent event) {
boolean condition = true;
for (int y : fullGuess) {
…
}
}
}

JavaFX. Register eventHandler in custom class

I try register eventHandler in my custom class. I don't know what interface or methods I have to implement for having addEventHandler method in my custom class. For this reason my Model class extends Rectangle (Rectangle class has addEventHandler mechanism).
Also I don't know why assigned source object not working (please see comment in Controller class).
Creating custom events I make by this tutorial: https://stackoverflow.com/a/27423430/3102393.
Project Structure
Controller
package sample;
import javafx.event.Event;
public class Controller {
private Model model;
public Controller() {
model = new Model();
model.addEventHandler(MyEvent.ROOT_EVENT, this::handler);
}
private void handler(MyEvent event) {
if(event.getEventType().equals(MyEvent.INSTANCE_CREATED)) {
// Why is event.getSource() instence of Rectangle and not instance of assigned MyObject?
Object obj = event.getSource();
System.out.println(event.getMyObject().getText());
}
}
public void clickedCreate(Event event) {
model.makeEvent();
}
}
Model
package sample;
import javafx.scene.shape.Rectangle;
import java.util.ArrayList;
public class Model extends Rectangle {
private ArrayList<MyObject> objects = new ArrayList<>();
private Integer counter = 0;
public void makeEvent() {
MyObject object = new MyObject((++counter).toString() + "!");
objects.add(object);
fireEvent(new MyEvent(object, null, MyEvent.INSTANCE_CREATED));
}
}
Custom event MyEvent
package sample;
import javafx.event.Event;
import javafx.event.EventTarget;
import javafx.event.EventType;
public class MyEvent extends Event {
public static final EventType<MyEvent> ROOT_EVENT = new EventType<>(Event.ANY, "ROOT_EVENT");
public static final EventType<MyEvent> INSTANCE_CREATED = new EventType<>(ROOT_EVENT, "INSTANCE_CREATED ");
public static final EventType<MyEvent> INSTANCE_DELETED = new EventType<>(ROOT_EVENT, "INSTANCE_DELETED");
private MyObject object;
public MyEvent(MyObject source, EventTarget target, EventType<MyEvent> eventType) {
super(source, target, eventType);
object = source;
}
public MyObject getMyObject() {
return object;
}
}
And finally MyObject
package sample;
public class MyObject {
private String text;
MyObject(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
Note (and question): I also tried using a ObservableList of instances of MyObjects, but I think that there is no notify for updating instance attribute.
Basics of Events
Events are fired using Event.fireEvent which works in 2 steps:
Build the EventDispatchChain using EventTarget.buildEventDispatchChain.
Pass the Event to the first EventDispatcher in the resulting EventDispatchChain.
This code snippet demonstrates the behaviour:
EventTarget target = new EventTarget() {
#Override
public EventDispatchChain buildEventDispatchChain(EventDispatchChain tail) {
return tail.append(new EventDispatcher() {
#Override
public Event dispatchEvent(Event event, EventDispatchChain tail) {
System.out.println("Dispatch 1");
tail.dispatchEvent(event);
return event;
}
}).append(new EventDispatcher() {
#Override
public Event dispatchEvent(Event event, EventDispatchChain tail) {
System.out.println("Dispatch 2");
tail.dispatchEvent(event);
return event;
}
});
}
};
Event.fireEvent(target, new Event(EventType.ROOT));
It prints
Dispatch 1
Dispatch 2
As you can see, the way the EventTarget constructs the EventDispatchChain is totally up to the EventTarget.
This explains why you have to implement addEventHandler ect. yourself.
How it's done for Nodes
This is described in detail in the article JavaFX: Handling Events - 1 Processing Events on the Oracle website.
The important details are:
Different source objects are used during the event handling.
EventHandlers / EventFilters are used during the event dispatching (2.).
This explains why the source value is unexpected.
How to implement addEventHandler
It's not that hard to do this, if you leave out the event capturing and bubbling. You just need to store the EventHandlers by type in a Map<EventType, Collection>> and call the EventHandlers for each type in the EventType hierarchy:
public class EventHandlerTarget implements EventTarget {
private final Map<EventType, Collection<EventHandler>> handlers = new HashMap<>();
public final <T extends Event> void addEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler) {
handlers.computeIfAbsent(eventType, (k) -> new ArrayList<>())
.add(eventHandler);
}
public final <T extends Event> void removeEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler) {
handlers.computeIfPresent(eventType, (k, v) -> {
v.remove(eventHandler);
return v.isEmpty() ? null : v;
});
}
#Override
public final EventDispatchChain buildEventDispatchChain(EventDispatchChain tail) {
return tail.prepend(this::dispatchEvent);
}
private void handleEvent(Event event, Collection<EventHandler> handlers) {
if (handlers != null) {
handlers.forEach(handler -> handler.handle(event));
}
}
private Event dispatchEvent(Event event, EventDispatchChain tail) {
// go through type hierarchy and trigger all handlers
EventType type = event.getEventType();
while (type != Event.ANY) {
handleEvent(event, handlers.get(type));
type = type.getSuperType();
}
handleEvent(event, handlers.get(Event.ANY));
return event;
}
public void fireEvent(Event event) {
Event.fireEvent(this, event);
}
}

Minimal implementation of JavaFX TextInputArea

I'm investigating the best way to write a rich text editor in JavaFX - don't mention the HTMLEditor to me: we've spent literally months hacking at it and I could write reams about why it isn't suitable for our purposes! Choice at the moment is to extend AnchorPane and do all of the layout, navigation etc. from scratch or to extend TextInputArea, which looks as though it would help. Anyone have their own implementation of that or would like to propose a minimal implementation?
FWIW here's a scrap from me:
public class TryPain3 extends TextInputControl {
private AnchorPane rootNode = new AnchorPane();
public TryPain3() {
super(new Content() {
private String text = "";
#Override
public String get(int i, int i1) {
return text.substring(i, i1);
}
#Override
public void insert(int i, String string, boolean bln) {
}
#Override
public void delete(int i, int i1, boolean bln) {
}
#Override
public int length() {
return text.length();
}
#Override
public String get() {
return text;
}
#Override
public void addListener(ChangeListener<? super String> cl) {
}
#Override
public void removeListener(ChangeListener<? super String> cl) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public String getValue() {
return text;
}
#Override
public void addListener(InvalidationListener il) {
}
#Override
public void removeListener(InvalidationListener il) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
setEditable(true);
Text text1 = new Text("fred was here");
text1.setFont(Font.font("Tahoma", FontWeight.NORMAL, 18));
text1.setTextAlignment(TextAlignment.LEFT);
text1.setFontSmoothingType(FontSmoothingType.LCD);
rootNode.getChildren().add(text1);
setSkin(new TP3Skin(this, rootNode));
}
class TP3Skin implements Skin<TryPain3> {
TryPain3 tp;
Node root;
public TP3Skin(TryPain3 tp, Node root) {
this.tp = tp;
this.root = root;
}
#Override
public TryPain3 getSkinnable() {
return tp;
}
#Override
public Node getNode() {
return root;
}
#Override
public void dispose() {
tp = null;
rootNode = null;
}
}
}
It looks as though the skin is not optional.
Questions I'd like to find out are things like:
how is the UI supposed to be drawn - I'm quite happy to code it from scratch but how to get benefit of calls to forward() as an example
should the UI creation be done in the Skin?
whether the base class deals with things like where to put the cursor if you click on a bit of text
I'm sure other questions will arise from this.
You may want to try next JavaFX 8.0 control TextFlow, which allows aggregation of various text styles. See examples here: https://wikis.oracle.com/display/OpenJDK/Rich+Text+API+Samples
JavaFX 8 is part of JDK8. So you can download developers build here http://jdk8.java.net/download.html and it will include JavaFX and new TextFlow control.

Resources