How to force combobox to render autocomplete options? - java

This is my zul code:
<combobox id="digitalPublisherCombobox" value="#load(ivm.inventory.digitalPublisherName)"
onOK="#command('setDigitalPublisher', digitalPublisherBox = self)"
onSelect="#command('setDigitalPublisher', digitalPublisherBox = self)"
onChanging="#command('setupQuicksearchByEvent', searchlayout = event, prefix = 'PUB', tags = 'PublisherName, PublisherNameTranslit')"
mold="rounded" hflex="1" buttonVisible="false" autodrop="true">
<comboitem self="#{each=entry}" value="#{entry.key}" label="#{entry.value}"/>
</combobox>
And this is QuickSearch implementations:
#Command
public void setupQuicksearchByEvent(#BindingParam("searchlayout")Event event, #BindingParam("prefix") String prefix, #BindingParam("tags") String tags) throws WrongValueException, SearchException, IOException
{
if(event instanceof InputEvent)
{
InputEvent inputEvent = (InputEvent) event;
String inputText = inputEvent.getValue();
List<String> searchFields = Arrays.asList(tags.split(","));
ListModel model = new ListModelMap(ZKLogic.findDocsStartingWith(prefix, searchFields, "proxy", inputText), true);
ListModel subModel = ListModels.toListSubModel(model, Autocompleter.MAP_VALUE_CONTAINS_COMPARATOR, 10);
Combobox searchBox = (Combobox) event.getTarget();
searchBox.setModel(subModel);
searchBox.setItemRenderer(new ComboitemRenderer()
{
#Override
public void render( Comboitem item, Object data, int pos ) throws Exception
{
String publisherString = data.toString();
UID key = getUidFromPublisherString(publisherString);
int startIndex = publisherString.indexOf('=') + 1;
String publisher = publisherString.substring(startIndex);
item.setLabel(publisher);
item.setValue(key);
}
});
}
}
ZKLogic.findDocsStartingWith return map with UID-key and String-value.
With code above I achieved to get dropdown list when I switch to another window. I need to type something, then select another browser or notepad window - and comboitems will be displayed immediately.
So, my question still need answer, is there are any techniques to reproduce this windows switching in code? Or maybe I should do something with autocomplete, because I've got some ac working with preloaded lists, but this thing should return only 10 records from db, instead of all 70000 entries, every time when user type something in the field.
Edit 20/09/2013: Problem still exist. Rename question a bit, because thing that I need is to call render option by force in code. Is there is any way to do it? Code hasn't changed a lot, but print option in render method said, that method can miss two or more onChange events and suddenly render text for one variant.
Maybe you know another autocomplete options in zk framework where database participating? I'm ready to change implementation, if there is a guide with working implementation of it.

Ok I see two problems, you should solve first.
Setting the Renderer in every call of setupQuicksearchByEvent(...).
that is not logical, cos it is the same every time.
Add to the zul combobox tag something like
itemRenderer="#load(ivm.myRenderer)" ....
If you want just 10 items, do not let the db-request return more then 10.
If you use JPA klick here or for sql here or just google a bit.
After you fixed this two issues, we can exclude these as a reason of the unexpected behavior and fix it, if it is still present.
Edit
Ok, I have two possible ways to fix it.
Call Combobox#invalidate()
This schould force zk to rerender the Combobox, but could
lead to low performance and I would not prefer this.
Use Listbox with the select mold instead of Combobox.
To force the rerender, use Listbox#renderAll()

Try setting the selected item on your combobox or throw its related event

Solution is simple. Really. Nothing is better then brute-force, but I think I tried to avoid it and use it in despair.
#Command
public void setupQuicksearchByEvent(#BindingParam("searchlayout")Event event, #BindingParam("prefix") String prefix, #BindingParam("tags") String tags) throws WrongValueException, SearchException, IOException
{
if(event instanceof InputEvent)
{
InputEvent inputEvent = (InputEvent) event;
String inputText = inputEvent.getValue();
List<String> searchFields = Arrays.asList(tags.split(","));
Map<UID, String> publishers = ZKLogic.findDocsStartingWith(prefix, searchFields, "proxy", inputText);
Combobox searchBox = (Combobox) event.getTarget();
searchBox.getChildren().clear();
for (Map.Entry<UID, String > entry : publishers.entrySet())
{
Comboitem item = new Comboitem();
item.setLabel(entry.getValue());
item.setValue(entry.getKey());
searchBox.appendChild(item);
}
}
}

Related

Where should I validate JavaFX Property changes?

I have a mvp structured javafx application. There is a view with a textfield, which has its own textProperty of type StringProperty. There is also a model which contains an Object called Item. Item has an IntegerProperty.
Now I'd like to bind these two Properties within my presenter-class, so that they get updated, when one or another changes. Eventhough they have different types, there is the possibility to bind them the following way:
Bindings.bindBidirectional( textField.textProperty(), item.percentProperty(), new NumberStringConverter() );
This works perfectly fine, unless the value of the textfield gets cleared, which results in a NullPointerException, because an empty value of textProperty results in a Null-Value and setting a null Value in IntegerProperty results in a NullPointerException. Can you think of any way to avoid this? Do I have to write my own NumberStringConverter?
Moreover I'd like to define, that Item can only hold a percent value between 0 and 100. The View should be informed, when the value is invalid, so the user can get feedback. Where should I verify these kind of businessrules?
I came up with a first example, but I am not sure, if that should be the way to go, so I'd be curious, if you might have better ideas how to solve this.
class PercentProperty extends SimpleIntegerProperty
{
private InvalidValueListener invalidValueListener = null;
public PercentProperty ( final Integer defaultValue )
{
set( defaultValue );
}
#Override
public void set( final int newValue )
{
if ( isValid( newValue ) )
{
super.set( newValue );
if ( invalidValueListener != null )
invalidValueListener.validValue();
}
else
{
if ( invalidValueListener != null )
invalidValueListener.invalidValue();
}
}
private boolean isValid( final int value )
{
return (value >= 0 && value <= 100);//FIXME: Better use Predicates to define Rules.
}
public void setListener( final InvalidValueListener listener )
{
invalidValueListener = listener;
}
public void removeListener( #SuppressWarnings( "unused" ) final InvalidValueListener listener )
{
invalidValueListener = null;
}
protected void fireInvalidationValue()
{
invalidValueListener.invalidValue();
}
}
interface InvalidValueListener
{
void validValue();
void invalidValue();
}
JavaFX is a simple graphical toolkit, not a comprehensive framework, and this means that lots of things you have to engineer yourself. Data validation is such a thing, and you have to find your own way among your previous experience and others' suggestions.
I would not bind the two properties: the text field should be initialized (just set, not bound, to avoid glitches while the user is typing without her explicit consensus) with the value from the model, and then the integer property should be updated by a listener (a text field's ChangeListener or a listener to the form submission, if appliable and depending on your likes), which is responsible for validating input and reporting errors to the user.
This way you decouple two things that are indeed unrelated: one is a widget for accepting user input (a text you need to parse to get a number), and the other is a number in your model, which is used to make a computation.
As a side note, I would not use two properties altogether, and I'd revisit your three tiers parition. MVP and all MVC derivatives proved to be good patterns to build GUI toolkits, but I was never convinced they were equally good for structuring GUI applications. I mean, if what you call model is a way to share session data between different parts of the application (kind of an events sink) then it's a perfectly legitimate implementation, otherwise I see no use in having a separate bunch of properties grouped in a class. In the latter case, the widgets themselves are the model:
// This is the controller
public class PesonalDetails {
// Model starts here: it's implicitely defined by the widgets
// You may also use #FXML
private final TextField first = new TextField();
private final TextField last = new TextField();
// Model ends here
}
Note I'm not saying MVC should be thrown away and everything should be collapsed in one single file. Just that MVC, MVP, MVVM are design patterns and it's up to you to decide when, where and how to implement them - depending on how much they buy to you. With JavaFX I like to use these tiers:
A visual layout tier (a layout builder implemented in Java or FXML)
Event handling code
If appliable, a data access layer (and you can apply a pattern here, like ActiveRecord)
(The new version of the answer)
I think the best aproach is to not let a user enter an incorrect value in the first place. You can achive this easily with help of JideFX Fields:
FormattedTextField<Integer> field = new FormattedTextField<>();
field.getPatternVerifiers().put("p", new IntegerRangePatternVerifier(0, 100));
field.setPattern("p");
field.valueProperty().bindBidirectional(item.percentProperty());
Particularly FormattedTextField is very convenient because it do text-to-value conversion and validation for you, so there is no need to implement any utility classes yourself.
Links:
JideFX Fields Developer Guide: http://www.jidesoft.com/jidefx/JideFX_Fields_Developer_Guide.pdf
Source code: https://github.com/jidesoft/jidefx-oss
Binary: http://search.maven.org/#search%7Cga%7C1%7Cjidefx

Dynamically add and remove components without AJAX?

I have a dynamic form that I'm writing in Wicket with a handful of forms that get duplicated with a "Click here to add more issues" type of button. I've written a very basic (I'm still new to Wicket) AJAXy listener that mostly works, but I can't figure out how to remove or even hide the items in my ListView.
This makes me wonder, is there any way to just have some JS duplicate the form fields? Before I retooled the form with Wicket components I had the Jquery Dynamic Form Plugin duplicating the values. This worked great and was very easy to understand (an important plus). However I can't figure out how this would affect Wicket if I simply used the plugin instead of something like
//Issue box magic
final MarkupContainer rowPanel = new WebMarkupContainer("issuesPanel");
rowPanel.setOutputMarkupId(true);
form.add(rowPanel);
ArrayList numIssues = new ArrayList();
numIssues.add(new Object());
numIssues.add(new Object());
numIssues.add(new Object());
final ListView lv = new ListView("issuesBox", numIssues) {
#Override
protected void populateItem(ListItem item) {
int index = item.getIndex() + 1;
item.add(new DropDownChoice("issues", combinedIssues));
item.add(new TextField<String>("note"));
}
};
lv.setReuseItems(true);
rowPanel.add(lv);
form.add(new AjaxSubmitLink("addIssue", form) {
#Override
public void onSubmit(AjaxRequestTarget target, Form form) {
lv.getModelObject().add(new Object());
if (target != null)
target.add(rowPanel);
}
}.setDefaultFormProcessing(false));
form.add(new AjaxSubmitLink("removeIssue", form) {
#Override
public void onSubmit(AjaxRequestTarget target, Form form) {
//Wicket gets very angry when you remove components, so just hide it (recommended way)
if (target != null) {
Component lastObject = (Component)lv.get(lv.getList().size() - 1);
lastObject.setVisible(false);
log.debug("Components " + lv.get );
}
}
}.setDefaultFormProcessing(false));
The JQuery plugin is much easier to use, but how can I tell Wicket that there are more fields than it thought there were?
Note I'm also trying to avoid the AJAX call just to add a new issue which in the siltation I'm using the app in might become a problem.
Any suggestions?
You can't just add form elements in html via ajax. With Wicket, you have a compenent tree in html and Java, and both must match. In the end, Wicket must know what todo with the values when you submit the form.
Not sure I understand your particular requirements, but I guess a similar problem might be that of adding adresses to an person. Here, I would build a AdressEditPanel that contains a form with all the fields that are required for one adress. That Panel would have an PersonAdress (as an example) Object as Model.
On the Person, you would have an Collection of Adresses and use a ListView to render and edit each Adress. In the populateItem() function of the ListView you would add one instance of a AdressEditPanel to the item.
If you need to add an Adress to an person, simply add an entry to the collection of adresses and redisplay the form (I would work with out Ajax first, and once it works do the minimal change required to switch to ajax).
Hope that helps
If you invoke removeAll() on ListView after you have modified its model object you should solve your problem. For example
new AjaxSubmitLink("addIssue", form) {
#Override
public void onSubmit(AjaxRequestTarget target, Form form) {
lv.getModelObject().add(new Object());
lv.removeAll();
if (target != null)
target.add(rowPanel);
}
However I don't know if this could cause problems to form validation, but I think it should be safe.
UPDATE
If you want to apply the same technique for removing link you should write something like this:
new AjaxSubmitLink("removeIssue", form) {
#Override
public void onSubmit(AjaxRequestTarget target, Form form) {
if (target != null) {
lv.getModelObject().remove(lv.getList().size() - 1);
lv.removeAll();
target.add(rowPanel);
}
}
}
However without AJAX this is not possible. The only way is to use JS and on the server side read the request parameters coming from form.

How can I (un)hide a SWT TableItem?

I am trying to allow my user to search through a table of information, dynamically hiding/showing results that contain the search. I have the hiding part down, and it works well, but I'm having trouble showing the table item again once the search criteria is changed.
Here is my hide code:
searchField.addModifyListener(new ModifyListener() {
#Override
public void modifyText(ModifyEvent arg0) {
modified = true;
for (int i = 0; i < table.getItems().length; i++) {
if (!(table.getItem(i).getText(2)
.contains(searchField.getText()))) {
table.getItem(i).dispose();
}
}
if ("".equals(searchField.getText())) {
modified = false;
//where I would want to un-hide items
}
}
});
Looking at your code, it seems you try to hide the item by calling dispose(). If you dispose a widget, it is gone for good. You cannot get it back.
If you want to unhide it again, will have to create a new item at the position of the previously hidden one with the same content.
Isn't it better to actually operate with some kind of a table model and JFace bindings, rather, then do it like that? And yes, disposing is not hiding. You should probably remove the item from the table.
You have probably to save the data from TableItem into collection before you call dispose. Then when you search again you could check that collection and if matches are found, then insert back into Table by creating new TableItem.

my jComboBox does not react to my keyListener and actionPerform performs weired stuff

I am trying to search for UserName and return values onto jComboBox, here is the code
public void actionPerformed(java.awt.event.ActionEvent e) {
sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));
usrList = sr.searchUser();
String[] userList = new String[usrList.size()] ;
for(int i=0;i<usrList.size();i++){
userList[i]= usrList.get(i).getUserName();
}
model = new DefaultComboBoxModel(userList);
jComboBoxReceiver.setModel(model);
}
after you click to somewhere else or click enter,it will conduct the search, however, it will go search for the first item again, which is very confusing... then i tried using key Pressed
if(e.getKeyCode()==13){
sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));
usrList = sr.searchUser();
String[] userList = new String[usrList.size()] ;
for(int i=0;i<usrList.size();i++){
userList[i]= usrList.get(i).getUserName();
}
model = new DefaultComboBoxModel(userList);
jComboBoxReceiver.setModel(model);
}
And this one does not react at all.
You need to set the listener(s) on the Editor not the ComboBox itself. See the answer here:
Detecting when user presses enter in Java
Wow, you're rebuilding a ComboBoxModel each time ? Isn't it a little expensive ? You know there is a MutableComboBoxModel, also implemented by DefaultComboBoxModel that would allow you to add/remove elements from you combobox without rebuilding its model each time ?
Concerning your question, I don't understand the statement
However, if i do that, it does perform correctly, however, it will go search for the first item again
Do you mean your JComboBox starts to blink with content being modified each time ?
if so, maybe is it because your ActionListener is linked to JComboBox, which content changes continuously.
Anyway, i suggest you add some logs, like
sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));
DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBoxReceiver.getModel();
model.remvoeAllElements();
usrList = sr.searchUser();
String[] userList = new String[usrList.size()] ;
for(int i=0;i<usrList.size();i++){
String username = usrList.get(i).getUserName();
System.out.println(username); // feel free to instead use one loger
model.addElement(username);
}
Besides, i would tend to suggest you an other approach, in which combo box model don't contain simple Strings, but rather User objects, with a ListCellRenderer displaying only the user name.
IMO, what will really be confusing for your users is to have the content and selection of a combo box changed as soon as they select one of its options.
Anyway, if you really want to do that, then you should remove the action listener (or deactivate it) before changing its content, and re-add it (or reactivate it) after :
public void actionPerformed(java.awt.event.ActionEvent e) {
sr = new Search(((String) jComboBoxReceiver.getSelectedItem()));
usrList = sr.searchUser();
String[] userList = new String[usrList.size()] ;
for(int i=0;i<usrList.size();i++){
userList[i]= usrList.get(i).getUserName();
}
model = new DefaultComboBoxModel(userList);
jComboBoxReceiver.removeActionListener(this);
jComboBoxReceiver.setModel(model);
jComboBoxReceiver.addActionListener(this);
}

CheckboxCellEditor shows text and not a check box

I'm using the following
org.eclipse.jface.viewers.CheckboxCellEditor.CheckboxCellEditor(Composite parent)
I'm creating a table viewer with cellEditors and doing the following
CellEditor[] editors = new CellEditor[columnNames.length];
editors[7] = new CheckboxCellEditor(table);
I have a CellModifier that has the following
public Object getValue(Object element, String property) {
Object result = null;
...
result = Boolean.valueOf(task.isDfRequested());
return result;
}
public void modify(Object element, String property, Object value) {
item.isSelected(((Boolean)value).booleanValue());
}
Finally I have a LabelProvider that has the following
public String getColumnText(Object element, int columnIndex) {
String result = "";
try {
result = Boolean.toString(item.isSelected());
} catch (Exception ex) { }
break;
However, in my UI instead of having a check box I have the word true or false && clicking it results in switching state to false or true. Any ideas on why I don't have a checkbox??
I've searched in the source code of CheckboxCellEditor class and in the constructor the control associated to the CellEditor is created in the createControl(Composite parent) method. This method is abstract in CellEditor class and it's implemented like this in CheckboxCellEditor:
protected Control createControl(Composite parent) {
return null;
}
So a control is not created, that's why you don't see the checkbox. In the documentation of the Class you can read:
Note that this implementation simply
fakes it and does does not create any
new controls. The mere activation of
this editor means that the value of
the check box is being toggled by the
end users; the listener method
applyEditorValue is immediately called
to signal the change.
I solved this using a ComboBoxCellEditor with yes and no items.
Regards.
Well, I have no idea how SWT works or what component you are even talking about.
But I do know that when using Swing you can have custom editors for a column in a JTable. If you don't tell the table the class of data for the column then the toString() method of the data is invoked. But if you tell the table that Boolean data is displayed in the column then the table will use the check box editor.
Sounds like a similiar symptom, but I don't know your particular solution.
What I've decided to do is to just implement a dirty hack others have been using.
Create two images of check boxes, one checked the other not checked. Switch the state between the two based on the boolean.
It's not perfect, but for now it gets the job done

Categories

Resources