Important Notice - Forums is archived
To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
Switch Component
Hi fellow Vaadin users,
inspired by the iPhone, I decided to create a Switch component. On the server-side the component extends CheckBox but with a different client-side implementation.
The state of the switch can be changed by clicking with mouse, dragging with mouse or with keyboard by first focusing the component (tab) and then pressing space bar.
See live demo, Vaadin 6.2+ compatible switch-0.91.jar and source code.
The component is not yet thoroughly tested (and not at all with IE) so there might still be some bugs.
Wow ! Looks great !
Does it allow to change default ON/OFF labels ?
P.S. I think it's time to go build new default widgetset with that cool extra widgets. And a question - maybe it is time to make a pool and vote for extra/contrib widgets which deserves inclusion into the Vaadin core ?
Dmitri L Livotov:
Does it allow to change default ON/OFF labels ?
Yes, the default ON/OFF graphics can easily be changed with a single image file and some CSS in your theme. I have plans to include few other styles in the component as examples on how to do that.
Hi,
just wanted to let you know that I updated the Switch component to version 0.92.
Changes to the previous version include:
- Support for Mobile Safari touch events.
- Updated demo application.
- Some bugfixes.
For more details and a download link, go to Switch at Vaadin Directory.
Hi,
First of all thanks for this nice component, it's really usefull.
But now that I am using it, I found a rather annoying issue:
Whenever I set the switch to read-only, the switchbox is actually turned to the off state, even if I set the value to "true" before.
This is an example of how I use it (in a Table):
Item item = container.addItem(newComponent.getId());
item.getItemProperty(DB_COLNAME_ID).setValue(newComponent.getId());
item.getItemProperty(DB_COLNAME_NAME).setValue(newComponent.getName());
item.getItemProperty(DB_COLNAME_DESCRIPTION).setValue(newComponent.getDescription());
item.getItemProperty(DB_COLNAME_ENABLED).setValue(new Switch("", true));
-> using this code the switchbox is rendered correctly, namely in the "on" state.
But when I make it readonly using the code below, the switchbox is rendered with the "off" state:
((Switch) item.getItemProperty(DB_COLNAME_ENABLED).getValue()).setReadOnly(true);
This bug prevents me from generating a read-only listing of my component statuses.
Any chance you can fix this ?
Thanks for the feedback and the bug report!
Sounds like fixing this issue would be quite quick to fix to the component. I'll try to find some time later today or next week to look into this issue in more detail and release a new fixed version in the Directory.
- Teemu
I just uploaded a new version of the Switch add-on to the Directory. The new version is labeled 0.93 and contains few bugfixes listed below.
- The read-only mode is now fixed (thanks to Guy DS for reporting this issue).
- Some keyboard navigation issues should now be resolved.
Please let me know if you still have any issues with the component.
- Teemu
Thanks for the quick fix, I'll try it out later today.
I also have a feature request, but I'm not sure if it's easy to implement:
It would be nice if I could also sort a table based on the state of the switches in that table.
So by clicking on the header of the column with the switches, the table would be sorted with all "on switches" at the
top (or at the bottom, depending on the ascending/descending status)
Guy DS
I just tested the new version (0.93) and the read-only mode now works as expected. Thanks.
But now I have another problem :)
The problem that I'm seeing now is that the ValueChangeEvent is not fired when I toggle one of the switch boxes inside the table.
This is my code:
Item item = container.addItem(newComponent.getId());
item.getItemProperty(DB_COLNAME_ID).setValue(newComponent.getId());
item.getItemProperty(DB_COLNAME_NAME).setValue(newComponent.getName());
item.getItemProperty(DB_COLNAME_DESCRIPTION).setValue(newComponent.getDescription());
Switch newSwitch = new Switch("", false);
newSwitch.addListener(new Property.ValueChangeListener()
{
public void valueChange(ValueChangeEvent event)
{
mainWindow.showNotification("switch button changed its state");
}
});
newSwitch.setImmediate(true);
item.getItemProperty(DB_COLNAME_ENABLED).setValue(newSwitch);
But when I click a switch button to toggle its state, the valueChange method doesn't get called
(and of course the message "switch button changed its state" is also not displayed)
Can this be because the switch button is inside a table ?
If so, any ideas how I can get this workikng inside a table ?
Ok, never mind, now it is suddenly working for some reason.
It might have been a caching issue or something of eclipse.
Ok, great!
Regarding the sorting, you could have the sorting functionality inside Table by simply extending the Switch class and implementing the java.lang.Comparable in the extended class.
- Teemu
Ok, thanks for the info, I will definitely try that out.
Is it possible to implement the java.lang.Comparable interface by default in the Switch box ?
Or isn't that an option ?
Yes, it would be possible to implements Comparable directly in the Switch component and I'll consider doing that in the next release.
In the mean time you can do this yourself by extending the Switch class in case you don't want to wait for the release. :)
- Teemu
Teemu Pöntelin: Yes, it would be possible to implements Comparable directly in the Switch component and I'll consider doing that in the next release.
Thanks, that would be really nice.
Teemu Pöntelin:
In the mean time you can do this yourself by extending the Switch class in case you don't want to wait for the release. :)- Teemu
Well, this is exactly what I did this afternoon because I need to release a first (beta) version of my application by the end of the week :D
Hi.
We seem to be having problem since we updated Vaadin to version 6.6.0 (and GWT to 2.3.0). We cannot compile the widgetset. We get this error:
[ERROR] Errors in 'jar:file:/Users/geoffrey16/.m2/repository/org/vaadin/addons/switch/0.93/switch-0.93.jar!/org/vaadin/teemu/switchui/widgetset/client/ui/touch/TouchEvent.java'
[ERROR] Line 19: The return type is incompatible with NativeEvent.getTouches()
[ERROR] Line 19: Methods cannot be overridden in JavaScriptObject subclasses
It seems that you are trying to override a final method.
After a quick look, it seems that the getTouches() method was introduce in GWT 2.2.0.
Any ideas how to work around this?
Thanks.
P.S: We need to use GWT 2.3 so downgrading GWT is not an option.
Hi Geoffrey,
thanks for reporting this issue. I fixed this problem and released a new version 0.94 of the Switch add-on in the Directory.
This version should work with Vaadin 6.6.0. Please use the older 0.93 version for compatibility with older Vaadin versions.
If you still have any issues with the add-on, please let me know.
Hi.
And thanks a lot. Looks like it is working just fine... Again ;)
Thanks again for your very quick reply.
I had a difficult job finding this particular "Switch" add-on a second time. I knew it existed, but did not know the name.
Can you add the words "toggle" and "slider" to the description on this page, to enhance searching:
https://vaadin.com/directory#addon/switch
--Basil Bourque
Basil Bourque: I had a difficult job finding this particular "Switch" add-on a second time. I knew it existed, but did not know the name.
I did some minor additions to the description of the Switch component. Hopefully it's now a bit easier to find.
Hi Teemu,
this is a great add-on to Vaadin. Unfortunately it's not very easy to use in a multilingual environment especially when Vaadin is used to develop portlets for the Liferay portal server.
With Liferay (or any other product) you can change the language at any time and the UI should adopt to the language changes so all the labels should be replaced. But some languages have longer words that other languages and having the widget relying on images to display the ON/OFF, YES/NO etc labels is not that comfortable, that's at least the impression I had after looking briefly at an earlier version.
Have you ever tried using the switch in a I18N application? What would be your recommendations in such a scenario?
I was thinking about retrieving a CSS style name depending on the selected language and adding that style name to the widget and depending on the style name display different labels but as I said... not very comfortable.
Cheers,
Alex
Alex Weirig:
Have you ever tried using the switch in a I18N application? What would be your recommendations in such a scenario?
Hi Alex,
and thank you for your feedback. As you already noticed the Switch add-on do not support any I18N features. The component is built from an image containing the ON/OFF text so changing the text would require you to draw new images for each supported language.
However with the latest release I experimented with adding the text via CSS in the "holodeck" theme (see styles.css:69). This is still far from optimal solution and I might add a server-side API for defining the localized texts in the future releases.
Also one option would be to use an image with universal icons instead of any text. The Vaadin TouchKit add-on uses the Switch and has an image of I / O instead of ON / OFF.
Marko Mitic: Do you plan to support vaadin 7?
I don't know about the plans but in my opinion using the new Vaadin 7 features for integrating Gwt widgets and Javascript you should easily be able to just find a library containing a gwt- or javascript-Switch component you like and integrate it yourself.
Check out the wiki for that: Vaadin 7 Wiki
Hi Marius Reinwald,
How to use switch component in vaadin 7?
I don't know if it is still necessary but in a quick break i made this rough port to Vaadin 7 (i worked with 7.3.5 when porting; no other versions tested). It just has basic functionality (Listener if value switch is flipped; flipping the switch programmatically; getter/setter for the Switch's value). SwitchComp is the "new" component, SwitchupdateUI is a small example on how to use it and "switchupdate" is the theme that includes the style of the Switch.
I'm gonna say that i won't continue working on the component. Any more functionality you might need you have to add yourself but the source code should give a good foundation. Most of the code is directly taken from the old Vaadin 6 source code (mainly the style.css which is almost a complete copy and the Widget class which was modified to suit the V7 communication. Other classes are mostly remade).
The source code is in the attachements. It's just source code, so it can't be directly imported as a project or as an external library. Either add the source code in the build path or create a new project, copy the code inside the new project, compile widgetset and such. Now you should be able to work with it, maybe even package it as a library if you want to.
If you need a "finished" and always supported Switch component you should use the one in Touchkit instead. This is just meant to be for the ones who can't/don't want to use Touchkit.
Hope this helps someone.
It seems that there really is a need to officially convert this add-on for Vaadin 7, so I finally took the time to upgrade Switch for Vaadin 7. The version 2.0.1 is now available at https://vaadin.com/addon/switch
Please notice that the latest version requires Vaadin 7.2+
Let me know if you find any bugs by commenting here or opening an issue on GitHub.
Hi ,
Switch state_changer = new Switch("", false);
state_changer.addValueChangeListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
logger.info(event.getProperty().getValue().toString());
}
});
state_changer.setImmediate(true);
am using above code in vaadin 7.3.3 My client side shows only checkbox
SuBiN SoMaN: My client side shows only checkbox
Have you compiled the widgetset? Please verify that your widgetset contains the Switch component.
For detailed instructions see:
https://vaadin.com/book/-/page/addons.eclipse.html
https://vaadin.com/book/-/page/addons.maven.html
i compiled the widgetset then also the same problem occurs
did you managed to show the images on the component? I still see the common checkboxes.
L.E.: I'm using it with vaadin 7.2.4
Checkbox appears in place of a Switch when the client-side implementation of the Switch component is missing from the widgetset. Please verify following things:
1) The widgetset is compiled and the following line appears in the compilation output:
Visiting SwitchConnector with ConnectorInitVisitor
2) The widgetset of your application (*.gwt.xml file) inherits the add-on with the following line:
<inherits name="org.vaadin.teemu.switchui.SwitchComponentWidgetset" />
An example of the application widgetset can be found in the demo application: https://github.com/tehapo/Switch/blob/master/switch-demo/src/main/resources/org/vaadin/teemu/switchui/demo/SwitchDemoWidgetset.gwt.xml
Thanks for the reply. But because your suggestion still did't helped me solving the issue, something else needs to be checked. So, before looking into the possible issues, here are a few excerts from the build log:
[INFO] Visiting SwitchConnector with ConnectorInitVisitor
[INFO] SwitchConnector will be in the eager bundle
[INFO] Will serialize class org.vaadin.teemu.switchui.client.SwitchState as a bean
The entries in my generated widgetset.xml file are correct, meaning that the component is found and the build log is certifying the clientside build has occured:
<inherits name="org.vaadin.teemu.wizards.WizardsforvaadinWidgetset" />
<inherits name="org.vaadin.teemu.switchui.SwitchComponentWidgetset" />
I've tried the component with a sample maven project is is displayed just fine, but my problem comes when I am trying to use it in a real-world existing application. So, do you have some hints on what else to debug or check in my app?
Hmm, in that case I'm running out of ideas. Have you tried to use any other add-ons with client-side widgets in the real-world project? The Wizards for Vaadin mentioned in your snippet doesn't have any client-side code, so that probably works fine.
I found out ... my mistake :( .
But for the sake of other developers benefit, I'll tell the story: my application is actually containing many "vaadin applications" in it, therefore in the web.xml I had separate init params for each vaadin servlet. Obviously, for one of the application (with the new addon), the widgetset reference was not valid for some reason. Correcting that it also corrected the add-on display.
there is still one thing still not functioning as expected: the animation and the button face image is not updated on clicks for styles other than holodeck.
Hi teemu, I noticed that if you place a Switch in a Table's generatedcell, it will not function correctly.
Setting the initial value does not render the correct UX in the client as it always displays as "ON". Value change correctly changes and sets the db value.
@Override
public Component generateCell(final Table source, final Object itemId, final Object columnId) {
@SuppressWarnings("rawtypes")
final Property property = source.getItem(itemId).getItemProperty(columnId);
Boolean selected = property != null ? (Boolean)property.getValue() : false;
Switch switchComponent = new Switch("", selected);
switchComponent.setImmediate(true);
switchComponent.addValueChangeListener(new ValueChangeListener(){ ...}
return switchComponent;
}
Even if manually set it to false, it displays as "ON"
@Override
public Component generateCell(final Table source, final Object itemId, final Object columnId) {
@SuppressWarnings("rawtypes")
Switch switchComponent = new Switch("", false);
switchComponent.setImmediate(true);
return switchComponent;
}
Example, all switches are set to false. The first two are in a table and the last is added to the layout.
Finally, for testing purpose, I switched the Switch to a CheckBox and it renders as expected with initial values. So I assume it is something with the js and drawing.
Hi Teemu --
It would be great to use the component in a Table/Grid, can you please assist to make this work ?
Thanks
Hi Teemu,
I am using the switch in a grid's DetailsGenerator -> same problem like the guys before :-(
The switch shows always "on".
Best regards,
Torsten
Thanks Teemu. I have the same problem and i will follow the issue :)
In my case i have a switch in a table cell. It works till i delete a row using
table.removeItem("itemId");
After that all switchers in a table are set to default state and freeze.