JavaFX. Register eventHandler in custom class - events

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);
}
}

Related

How to re-render Wicket component after the Event reception

I have a Wicket component which is listening for some event (IEvent). If such event arrives, I want to re-render the component with a changed model. There are no active controls on the page, like AjaxLink, which can trigger the re-rendering.
Is there a way to refresh such kind of component?
I was thinking to somehow trigger an AJAX request from the onEvent method and add an AjaxBehavior to the mentioned component. But I don't know, how to trigger the AJAX request.
public class PersonPanel extends Panel implements Observer {
private WebMarkupContainer wrapper;
public PersonPanel(String id) {
super(id);
setDefaultModel(new CompoundPropertyModel<PersonInfo>(getModel()));
wrapper = new WebMarkupContainer("wrapper");
wrapper.setOutputMarkupId(true);
add(wrapper);
wrapper.add(new Label("personID"));
// some more content
}
private IModel<PersonInfo> getModel() {
return new LoadableDetachableModel<PersonInfo>() {
#Override
protected PersonInfo load() {
// model loading logic
}
};
}
#Override
public void onEvent(IEvent<?> event) {
logger.debug("\n Person Panel received an Event: " + event.getPayload());
// Re-rendering of "wrapper" should be triggered from here.
}
#Override
public void update(Observable observable, Object o) {
send(this, Broadcast.EXACT, "Observable cache has changed.");
}
}
Here is the solution, thanks to hint from martin-g, solved via WebSockets. See the methods update and onEvent, plus added WebSocketBehavior on the component:
public class PersonPanel extends Panel implements Observer {
private WebMarkupContainer wrapper;
public PersonPanel(String id) {
super(id);
setDefaultModel(new CompoundPropertyModel<PersonInfo>(getModel()));
wrapper = new WebMarkupContainer("wrapper");
wrapper.setOutputMarkupId(true);
add(wrapper);
wrapper.add(new Label("personID"));
// some more content
add(new WebSocketBehavior() {
});
observableCache.addObserver(this);
}
private IModel<PersonInfo> getModel() {
return new LoadableDetachableModel<PersonInfo>() {
#Override
protected PersonInfo load() {
// model loading logic
}
};
}
#Override
public void onEvent(IEvent<?> event) {
if (event.getPayload() instanceof WebSocketPushPayload) {
WebSocketPushPayload wsEvent = (WebSocketPushPayload) event.getPayload();
wsEvent.getHandler().add(wrapper);
}
}
#Override
public void update(Observable observable, Object o) {
WebSocketSettings webSocketSettings =
WebSocketSettings.Holder.get(getApplication());
WebSocketPushBroadcaster broadcaster =
new WebSocketPushBroadcaster(webSocketSettings.getConnectionRegistry());
broadcaster.broadcastAll(
getApplication(),
new WebSocketMessage("WebSocket message from the PersonPanel."));
}
}
You can find a full running example project, implemented in Wicket 8 and Gradle on Bitbucket:
sw-samuraj/blog-wicket-spring-rest
At the send side you can pass the AjaxRequestTarget with the payload of the event.
send(getPage(), Broadcast.DEPTH, new MyPayload(target));
and then on the receive side:
MyPayload payload = (MyPayload) event.getPayload();
payload.getTarget().add(this);

Update UI from an AsyncTaskLoader

I've converted my AsyncTask to an AsyncTaskLoader (mostly to deal with configuration changes). I have a TextView I am using as a progress status and was using onProgressUpdate in the AsyncTask to update it. It doesn't look like AsyncTaskLoader has an equivalent, so during loadInBackground (in the AsyncTaskLoader) I'm using this:
getActivity().runOnUiThread(new Runnable() {
public void run() {
((TextView)getActivity().findViewById(R.id.status)).setText("Updating...");
}
});
I am using this in a Fragment, which is why I'm using getActivity(). This work pretty well, except when a configuration change happens, like changing the screen orientation. My AsyncTaskLoader keeps running (which is why I'm using an AsyncTaskLoader), but the runOnUiThread seems to get skipped.
Not sure why it's being skipped or if this is the best way to update the UI from an AsyncTaskLoader.
UPDATE:
I ended up reverting back to an AsyncTask as it seems better suited for UI updates. Wish they could merge what works with an AsyncTask with an AsyncTaskLoader.
It's actually possible. You essentially need to subclass the AsyncTaskloader and implement a publishMessage() method, which will use a Handler to deliver the progress message to any class that implements the ProgressListener (or whatever you want to call it) interface.
Download this for an example: http://www.2shared.com/file/VW68yhZ1/SampleTaskProgressDialogFragme.html (message me if it goes offline) - this was based of http://habrahabr.ru/post/131560/
Emm... you shouldn't be doing this.
because how an anonymous class access parent class Method or Field is by storing an invisible reference to the parent class.
for example you have a Activity:
public class MyActivity
extends Activity
{
public void someFunction() { /* do some work over here */ }
public void someOtherFunction() {
Runnable r = new Runnable() {
#Override
public void run() {
while (true)
someFunction();
}
};
new Thread(r).start(); // use it, for example here just make a thread to run it.
}
}
the compiler will actually generate something like this:
private static class AnonymousRunnable {
private MyActivity parent;
public AnonymousRunnable(MyActivity parent) {
this.parent = parent;
}
#Override
public void run() {
while (true)
parent.someFunction();
}
}
So, when your parent Activity destroys (due to configuration change, for example), and your anonymous class still exists, the whole activity cannot be gc-ed. (because someone still hold a reference.)
THAT BECOMES A MEMORY LEAK AND MAKE YOUR APP GO LIMBO!!!
If it was me, I would implement the "onProgressUpdate()" for loaders like this:
public class MyLoader extends AsyncTaskLoader<Something> {
private Observable mObservable = new Observable();
synchronized void addObserver(Observer observer) {
mObservable.addObserver(observer);
}
synchronized void deleteObserver(Observer observer) {
mObservable.deleteObserver(observer);
}
#Override
public void loadInBackground(CancellationSignal signal)
{
for (int i = 0;i < 100;++i)
mObservable.notifyObservers(new Integer(i));
}
}
And in your Activity class
public class MyActivity extends Activity {
private Observer mObserver = new Observer() {
#Override
public void update(Observable observable, Object data) {
final Integer progress = (Integer) data;
mTextView.post(new Runnable() {
mTextView.setText(data.toString()); // update your progress....
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreated(savedInstanceState);
MyLoader loader = (MyLoader) getLoaderManager().initLoader(0, null, this);
loader.addObserver(mObserver);
}
#Override
public void onDestroy() {
MyLoader loader = (MyLoader) getLoaderManager().getLoader(0);
if (loader != null)
loader.deleteObserver(mObserver);
super.onDestroy();
}
}
remember to deleteObserver() during onDestroy() is important, this way the loader don't hold a reference to your activity forever. (the loader will probably be held alive during your Application lifecycle...)
Answering my own question, but from what I can tell, AsyncTaskLoader isn't the best to use if you need to update the UI.
In the class in which you implement LoaderManager.LoaderCallback (presumably your Activity), there is an onLoadFinished() method which you must override. This is what is returned when the AsyncTaskLoader has finished loading.
The best method is to use LiveData, 100% Working
Step 1: Add lifecycle dependency or use androidx artifacts as yes during project creation
implementation "androidx.lifecycle:lifecycle-livedata:2.1.0"
Step 2: Create the loader class as follow, in loader create in public method to set the livedata that can be observed from activity or fragment. see the setLiveCount method in my loader class.
package com.androidcodeshop.asynctaskloaderdemo;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
import androidx.loader.content.AsyncTaskLoader;
import java.util.ArrayList;
public class ContactLoader extends AsyncTaskLoader<ArrayList<String>> {
private MutableLiveData<Integer> countLive = new MutableLiveData<>();
synchronized public void setLiveCount(MutableLiveData<Integer> observer) {
countLive = (observer);
}
public ContactLoader(#NonNull Context context) {
super(context);
}
#Nullable
#Override
public ArrayList<String> loadInBackground() {
return loadNamesFromDB();
}
private ArrayList<String> loadNamesFromDB() {
ArrayList<String> names = new ArrayList<>();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
names.add("Name" + i);
countLive.postValue(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return names;
}
#Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad(); // forcing the loading operation everytime it starts loading
}
}
Step 3: Set the live data from activity and observe the change as follows
package com.androidcodeshop.asynctaskloaderdemo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<ArrayList> {
private ContactAdapter mAdapter;
private ArrayList<String> mNames;
private MutableLiveData<Integer> countLiveData;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNames = new ArrayList<>();
mAdapter = new ContactAdapter(this, mNames);
RecyclerView mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
countLiveData = new MutableLiveData<>();
countLiveData.observe(this, new androidx.lifecycle.Observer<Integer>() {
#Override
public void onChanged(Integer integer) {
Log.d(TAG, "onChanged: " + integer);
Toast.makeText(MainActivity.this, "" +
integer,Toast.LENGTH_SHORT).show();
}
});
// initialize the loader in onCreate of activity
getSupportLoaderManager().initLoader(0, null, this);
// it's deprecated the best way is to use viewmodel and livedata while loading data
}
#NonNull
#Override
public Loader onCreateLoader(int id, #Nullable Bundle args) {
ContactLoader loader = new ContactLoader(this);
loader.setLiveCount(countLiveData);
return loader;
}
#Override
public void onLoadFinished(#NonNull Loader<ArrayList> load, ArrayList data) {
mNames.clear();
mNames.addAll(data);
mAdapter.notifyDataSetChanged();
}
#Override
public void onLoaderReset(#NonNull Loader loader) {
mNames.clear();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Hope this will help you :) happy coding

Demultiplex / delegate for GWT event system, using enums

I have an enum, say Fruits { Apple, Banana, Cherry }. I want to write a event subsystem for my application so that I can have the following pattern :
class AppleListener implements HasFruitPriceChangeListener<Apple> {
onFruitPriceChange(int newPrice) {
// do stuff
}
}
and a single listener, that can delegate tasks in the following format:
class FruitPriceListener {
public void onPriceChange(EnumMap<Fruits, Integer> pricePoints) {
// for each fruit, throw the event as
// FruitPriceChange.fire(Apple, newPrice);
}
}
Is there a way to do it in the above manner ? I would probably like to use ValueChangeEvent, but creating another 1 event and handler is also fine too. What I do not want to do is have event/class definitions for each item, like AppleFruitPriceChangeEvent, and so on.
You can use the EventBus for this things, which google suggested ( http://www.youtube.com/watch?v=PDuhR18-EdM ) Here how to use it.
Your globl Eventbus
public static SimpleEventBus bus = new SimpleEventBus();
Your change event:
import com.google.gwt.event.shared.GwtEvent;
import eyeweb.client.gwtMessages.JSPollingEntry;
public class EventModified extends GwtEvent<EventModifiedHandler> {
public final static Type<EventModifiedHandler> TYPE = new Type<EventModifiedHandler>();
private final Fruits fruits;
public final JSPollingEntry getPollingMessage(){
return fruits;
}
public EventModified(Fruits fruits) {
this.fruits = fruits;
}
#Override
public com.google.gwt.event.shared.GwtEvent.Type<EventModifiedHandler> getAssociatedType() {
return TYPE;
}
#Override
protected void dispatch(EventModifiedHandler handler) {
handler.onUpdateRecivde(this);
}
}
the handler for the event
package eyeweb.client.eventbus;
import com.google.gwt.event.shared.EventHandler;
public interface EventModifiedHandler extends EventHandler {
public void onUpdateRecivde(EventModified handler);
}
The event when something changes
EventBus.bus.fireEvent(new EventModified(fruite));
and the handler which gets the event
EventBus.bus.addHandler(EventModified .TYPE, new EventModifiedHandler() {
#Override
public void onMessageSend(EventSendData e) {
//... do stuff }
});
Well that sould be all ;)
Regards,
Stefan
So the solution I came up with was:
Create the enum, and associate a GwtEvent.Type with them:
enum Fruits {
Apple, Banana, Cherry;
public GwtEvent.Type getGwtEventType() {
return new GwtEvent.Type();
}
}
Create a new event.
class FruitPriceChangeEvent extends GwtEvent<?> {
private final Fruit fruit;
FruitPriceChangeEvent(Fruit fruitEnum) {
this.fruit = fruitEnum;
}
#Override
public GwtEvent.Type<?> getAssociatedType() {
return fruit.getGwtEventType();
}
// ... other stuff...
}
And then pass it through the whole event handler loop as #Stefan has mentioned. The beauty/hack of this approach is that the SimpleEventBus maintains a HashMap<GwtEvent.Type, List<HasHandlers>> from which to get the events, and everytime you create a new GwtEvent.Type it generates a unique hashcode (check the implementation for more details).
References:
http://grepcode.com/file/repo1.maven.org/maven2/com.google.gwt/gwt-servlet/2.1.1-rc1/com/google/gwt/event/shared/GwtEvent.java?av=f
http://grepcode.com/file/repo1.maven.org/maven2/com.google.gwt/gwt-servlet/2.1.1-rc1/com/google/gwt/event/shared/SimpleEventBus.java?av=f

GWT retrieve list from datastore via serviceimpl

Hi I'm trying to retrieve a linkedhashset from the Google datastore but nothing seems to happen. I want to display the results in a Grid using GWT on a page. I have put system.out.println() in all the classes to see where I go wrong but it only shows one and I don't recieve any errors. I use 6 classes 2 in the server package(ContactDAOJdo/ContactServiceImpl) and 4 in the client package(ContactService/ContactServiceAsync/ContactListDelegate/ContactListGui). I hope someone can explain why this isn't worken and point me in the right direction.
public class ContactDAOJdo implements ContactDAO {
#SuppressWarnings("unchecked")
#Override
public LinkedHashSet<Contact> listContacts() {
PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
String query = "select from " + Contact.class.getName();
System.out.print("ContactDAOJdo: ");
return (LinkedHashSet<Contact>) pm.newQuery(query).execute();
}
}
public class ContactServiceImpl extends RemoteServiceServlet implements ContactService{
private static final long serialVersionUID = 1L;
private ContactDAO contactDAO = new ContactDAOJdo() {
#Override
public LinkedHashSet<Contact> listContacts() {
LinkedHashSet<Contact> contacts = contactDAO.listContacts();
System.out.println("service imp "+contacts);
return contacts;
}
}
#RemoteServiceRelativePath("contact")
public interface ContactService extends RemoteService {
LinkedHashSet<Contact> listContacts();
}
public interface ContactServiceAsync {
void listContacts(AsyncCallback<LinkedHashSet <Contact>> callback);
}
public class ListContactDelegate {
private ContactServiceAsync contactService = GWT.create(ContactService.class);
ListContactGUI gui;
void listContacts(){
contactService.listContacts(new AsyncCallback<LinkedHashSet<Contact>> () {
public void onFailure(Throwable caught) {
gui.service_eventListContactenFailed(caught);
System.out.println("delegate "+caught);
}
public void onSuccess(LinkedHashSet<Contact> result) {
gui.service_eventListRetrievedFromService(result);
System.out.println("delegate "+result);
}
});
}
}
public class ListContactGUI {
protected Grid contactlijst;
protected ListContactDelegate listContactService;
private Label status;
public void init() {
status = new Label();
contactlijst = new Grid();
contactlijst.setVisible(false);
status.setText("Contact list is being retrieved");
placeWidgets();
}
public void service_eventListRetrievedFromService(LinkedHashSet<Contact> result){
System.out.println("1 service eventListRetreivedFromService "+result);
status.setText("Retrieved contactlist list");
contactlijst.setVisible(true);
this.contactlijst.clear();
this.contactlijst.resizeRows(1 + result.size());
int row = 1;
this.contactlijst.setWidget(0, 0, new Label ("Voornaam"));
this.contactlijst.setWidget(0, 1, new Label ("Achternaam"));
for(Contact contact: result) {
this.contactlijst.setWidget(row, 0, new Label (contact.getVoornaam()));
this.contactlijst.setWidget(row, 1, new Label (contact.getVoornaam()));
row++;
System.out.println("voornaam: "+contact.getVoornaam());
}
System.out.println("2 service eventListRetreivedFromService "+result);
}
public void placeWidgets() {
System.out.println("placewidget inside listcontactgui" + contactlijst);
RootPanel.get("status").add(status);
RootPanel.get("contactlijst").add(contactlijst);
}
public void service_eventListContactenFailed(Throwable caught) {
status.setText("Unable to retrieve contact list from database.");
}
}
It could be the query returns a lazy list. Which means not all values are in the list at the moment the list is send to the client. I used a trick to just call size() on the list (not sure how I got to that solution, but seems to work):
public LinkedHashSet<Contact> listContacts() {
final PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
try {
final LinkedHashSet<Contact> contacts =
(LinkedHashSet<Contact>) pm.newQuery(Contact.class).execute();
contacts.size(); // this triggers to get all values.
return contacts;
} finally {
pm.close();
}
}
But I'm not sure if this is the best practice...

gwt widget - mutually-exclusive toggle button

I want a hybrid of a ToggleButton and RadioButton.
I want the "mutually-exclusive" part of RadioButton, and the gui look and behavior of ToggleButton(up and down states).
Does one already exist?
I've adapted kirushik's solution and created a simple "ToggleButtonPanel" widget that takes an arbitrary number of ToggleButtons (and possibly any other widgets you'd like to add) and a panel of your choosing (defaults to VerticalPanel) and makes the buttons mutually exclusive.
What's nice about this is that the panel itself fires ClickEvents when the buttons are clicked. This way, you can add a single ClickHandler to the ToggleGroupPanel and then determine which button was clicked using event.getSource()
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class ToggleButtonPanel extends Composite implements HasWidgets, HasClickHandlers{
public ToggleButtonPanel() {
this(new VerticalPanel());
}
public ToggleButtonPanel(Panel panel){
this.panel = panel;
initWidget(panel);
}
#Override
public void add(Widget w) {
if(w instanceof ToggleButton){
ToggleButton button = (ToggleButton) w;
button.addClickHandler(handler);
}
panel.add(w);
}
#Override
public void clear() {
panel.clear();
}
#Override
public Iterator<Widget> iterator() {
return panel.iterator();
}
#Override
public boolean remove(Widget w) {
return panel.remove(w);
}
#Override
public void setWidth(String width) {
panel.setWidth(width);
};
#Override
public void setHeight(String height) {
panel.setHeight(height);
}
private final Panel panel;
private ClickHandler handler = new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Iterator<Widget> itr = panel.iterator();
while(itr.hasNext()){
Widget w = itr.next();
if(w instanceof ToggleButton){
ToggleButton button = (ToggleButton) w;
button.setDown(false);
if(event.getSource().equals(button)) {
button.setDown(true);
}
}
}
for(ClickHandler h : handlers){
h.onClick(event);
}
}
};
private List<ClickHandler> handlers = new ArrayList<ClickHandler>();
#Override
public HandlerRegistration addClickHandler(final ClickHandler handler) {
handlers.add(handler);
return new HandlerRegistration() {
#Override
public void removeHandler() {
handlers.remove(handler);
}
};
}
}
Here is my pure-gwt variant:
class ThreeStateMachine extends FlowPanel{
// This is the main part - it will unset all the buttons in parent widget
// and then set only clicked one.
// One mutual handler works faster and is generally better for code reuse
private final ClickHandler toggleToThis = new ClickHandler() {
#Override
public void onClick(ClickEvent clickEvent) {
for(Widget b: ThreeStateMachine.this.getChildren()){
((ToggleButton)b).setDown(false);
}
((ToggleButton)clickEvent.getSource()).setDown(true);
}
};
private ThreeStateMachine() { // Create out widget and populat it with buttons
super();
ToggleButton b = new ToggleButton("one");
b.setDown(true);
b.addClickHandler(toggleToThis);
this.add(b);
b = new ToggleButton("two");
b.addClickHandler(toggleToThis);
this.add(b);
b = new ToggleButton("three");
b.addClickHandler(toggleToThis);
this.add(b);
}
}
Surely, one'll need css styles for gwt-ToggleButton with variants (-up-hovering etc.)
I have something that is both not in an extension library, and not dependent on a panel like the other answers. Define this class which manages the buttons. We're adding a new click listener to the buttons, which is in addition to whatever click handler you attached in the "GUI Content" class. I can't copy and paste this in, so hopefully it's syntatically correct.
public class MutuallyExclusiveToggleButtonCollection {
List<ToggleButton> m_toggleButtons = new ArrayList<ToggleButton>();
public void add(ToggleButton button) {
m_toggleButtons.add(button);
button.addClickListener(new ExclusiveButtonClickHandler());
}
private class ExclusiveButtonClickHandler impelments ClickHandler {
public void onClick(ClickEvent event) {
for(ToggleButton button : m_toggleButtons) {
boolean isSource = event.getSource().equals(button);
button.setIsDown(isSource);
}
}
}
Came across the same need, heres another solution that does away with the separate handler and works nicely in UIBinder with a declaration like:
<my:RadioToggleButton buttonGroup="btnGroup" text="Button 1" />
Here's the extended class:
import java.util.HashMap;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.ToggleButton;
public class RadioToggleButton extends ToggleButton
{
private static HashMap<String,ButtonGroup> buttonGroups = new HashMap<>();
private ButtonGroup buttonGroup;
public #UiConstructor RadioToggleButton( String buttonGroupName )
{
buttonGroup = buttonGroups.get( buttonGroupName );
if( buttonGroup == null ){
buttonGroups.put( buttonGroupName, buttonGroup = new ButtonGroup() );
}
buttonGroup.addButton( this );
}
#Override
public void setDown( boolean isDown )
{
if( isDown ){
RadioToggleButton btn = buttonGroup.pressedBtn;
if( btn != null ){
btn.setDown( false );
}
buttonGroup.pressedBtn = this;
}
super.setDown( isDown );
}
private class ButtonGroup implements ClickHandler
{
RadioToggleButton pressedBtn = null;
public void addButton( ToggleButton button )
{
button.addClickHandler( this );
}
#Override
public void onClick( ClickEvent event )
{
Object obj = event.getSource();
if( pressedBtn != null ){
pressedBtn.setDown( false );
}
pressedBtn = (RadioToggleButton)obj;
pressedBtn.setDown( true );
}
}
}
gwt-ext toggleButtons
"This example illustrates Toggle Buttons. When clicked, such Buttons toggle their 'pressed' state.
The Bold, Italic and Underline toggle Buttons operate independently with respect to their toggle state while the text alignment icon Buttons belong to the same toggle group and so when one of them is click, the previously pressed Button returns to its normal state."
Register an additional ClickHandler on all the ToggleButtons.
For example, ToggleButtons home, tree, summary, detail.
public class Abc extends Composite implements ClickHandler {
ToggleButton home, tree, summary, detail
public Abc() {
// all your UiBinder initializations... blah, blah....
home.addClickHandler(this);
tree.addClickHandler(this);
summary.addClickHandler(this);
detail.addClickHandler(this);
}
#Override
public void onClick(ClickEvent p_event) {
Object v_source = p_event.getSource();
home.setDown(home==v_source);
tree.setDown(tree==v_source);
summary.setDown(summary==v_source);
detail.setDown(detail==v_source);
}
}
Of course, you just need to add all the other boilerplate code and register additional ClickHandlers for each ToggleButton.

Resources