Wicket form changes removed on ajax update - java

I have a pretty big and complex form which contains lots of form components.
On one of the drop down fields I have added a AjaxFormComponentUpdatingBehavior to handle changes in the drop down. Based on these changes I am updating some other fields in the form, this way:
masterFooDropDown.add(new AjaxFormComponentUpdatingBehavior("change") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
String value = (String) getFormComponent().getModelObject();
if (value != null) {
for (Foo foo: form.getModelObject().getFoos()) {
foo.setValue(value);
}
target.add(form);
}
}
});
The Foo fields gets updated correctly with the value from the drop down.
The problem is that any changes in the other text fields in the form is removed. I understand that this happens, since they have not been updated in the model.
How can I solve this?
Can I make all the filled in data in the form so far be written to the model in some way (without submitting the form)?
I need to add the whole form to the target in the ajax method since the fields that should be updated is children of the form model object and added to the form dynamically. For example, I cannot do target.add(fooFieldX) since there might be any number of "fooFields".

You can use AjaxFormComponentUpdatingBehavior/AjaxFormChoiceComponentUpdatingBehavior on all other form (choice) components so that they update the form's model object when modified.
You can use Component#visitChildren() and dynamically decide which particular form components to add to the AjaxRequestTarget, if it is easy to decide this. Even AjaxRequestTarget has method #addChildren() but it is not that flexible to filter the children components.

Related

How to trigger cell events after pasting data in a JavaFX grid?

I defined a paste method in a controller class, based on the solution given here: How to copy/paste table cells in a TableView. Everything went well, except for one detail: some cells where data is pasted have events that should be triggered but are not.
For example:
public class MyController {
private TableColumn<MyBean, String> valueColumn;
...
valueColumn.setOnEditCommit(e -> doSomeStuff(e));
private void doSomeStuff(CellEditEvent<MyBean, String> event) {
...
}
In this example, after user hits ENTER, the doSomeStuff method is called, which is expected behavior.
The problem with the paste method I implemented is that it does not affect the cell, only its content (its ObservableValue). This means of course that after data is pasted, no event is triggered.
My question : is there a way to trigger the same event, or a similar one that will call my doSomeStuff method after pasting data?
Table View doesn't work as you think. If you want to have a fully customizable structure, use a grid pane. It is hard to create one, but after you make it look like a table, you have many more options to customize.
I did that I a recent project where I was needed to insert a table inside a cell. It was much more easier with a gridpane and textfields.

How to sync view with model changes / rerender

I have a form that contains a text field input that is bound to a field in a model object. When a user enters data into that text field it can affect multiple other fields/components within the form based on calculations. My business logic is encapsulated in a service layer.
Theoretically the way I want this to work is that when the user updates the field, an ajax call is made to the server (on keypress) where the logic from the service is applied and all affected fields are updated on the model object. Once the model has been updated on the server, I want to sync the current state of the model object to the screen.
Is the only way to do this to refresh the entire screen? Is there a way to re-render only the components bound to the fields in the model that have changed? Also, if I refresh the screen, the field that is being edited is updated as well, is there a way to exclude this?
I am interested in any best practices for this technique.
Thanks
I assume from your tags that you're using wicket. Wicket uses Behaviors for this purpose. In the following example you will update both DropDownChoices if the input of the TextField changed. You just need to add those controls to the AjaxRequestTarget. Models of both DropDownChoices will be reloaded and rerendered at the frontend. Also make sure to call setOutputMarkupId(true) on controls you want to update.
TextField<String> textField = new TextField<String>("input");
Component dropDownA = new DropDownChoice<>("dropA").setOutputMarkupId(true);
Component dropDownB = new DropDownChoice<>("dropB").setOutputMarkupId(true);
textField.add(new AjaxFormComponentUpdatingBehavior("change") {
private static final long serialVersionUID = 1478280524536023725L;
#Override
protected void onUpdate(AjaxRequestTarget target) {
target.add(dropDownA);
target.add(dropDownB);
}
});
With Ajax you can update any Component you want, just make sure it has markup id (Component.setOutputMarkupId(true)).
You need to use AjaxFormComponentUpdatingBehavior or AjaxFormChoiceComponentUpdatingBehavior and in its onUpdate() callback you have to update the models of the respective FormComponents and then you can use FormComponent.this.getForm().visitChildren(FormComponent.class, IVisit) to visit all FormComponents of the current Form and add to AjaxRequestTarget only the ones you have updated.
Update
Another good solution (even better!) is to use Wicket Event bus. In the Ajax behavior you could broadcast an event:
component.send(getForm(), Broadcast.BREADTH, new UIChangedEvent(target, newValue));
where UIChangedEvent is your own class/POJO that brings the new value of the updated component and the AjaxRequestTarget.
Then the other FormComponents could override #onEvent() and use the value to calculate their new value and use the target to update themselves or not, depending on the earlier calculation.

I want to reset/reload a JFrame so all fields are set back to default value

I have several different text fields, combo boxes etc. I want to reset them all back to their defaults (as if the program was just opened) without doing it manually.. i.e. xField.text = "", or whatever.
I want to reset them all back to their defaults (as if the program was just opened) without doing it manually.
You will have to do it manually, but you can make it easier on yourself by organizing your code a bit.
For instance you can put your JTextComponents in an ArrayList<JTextComponent> and all other components of similar type into their own List as well. Then in your resetAll() method that you will write, iterate through all these lists resetting all components.
i.e.,
public void reset() {
// for all JTextFields and JTextAreas
for (JTextComponent textComponent: textComponentList) {
textComponent.setText("");
}
// for all JCheckBoxes and JRadioButtons
for (JToggleButton toggleButton: toggleButtonList) {
toggleButton.setSelected(false);
}
// iterate through other lists doing likewise
}
Another way, which I don't recommend is to recursively go through all the components of your GUI, getting the type via instanceof and then setting the components based on type.

How to create updateable panel using AjaxLink of Wicket?

I try to realize a link (in fact many links) that update a table in an website using an AjaxLink of Wicket. But I fail, the table is never updated (I have "setOutputMarkupId(true)" and call "setDefaultModelObject" and "addComponent", but there must be something other thats wrong).
How can I realize a panel with a number of links and a table that displays dynamic data, dependent on the link clicked? Can someone give an example (Maybe two links, when the first one is clicked the table displays two random numbers from 1-10, when the second is clicked the table displays random numbers from 1-100)? Without reloading the entire page, but only the html for the table?
One possible reason might be that you are not using a 'refreshable' model, but rather fetching the list items and passing them directly to the component, thus the list get's serialized in the session and doesn't get updated.
If this is the case, pass a LoadableDetachableModel (that retrieves the list in it's load method) to the component. I can't be more specific without seeing your code.
I don't think you've defined what you are doing very clearly.
Are these 2 tables different implementations? If so, then your code is correct - you have to replace the old component with the new one, then add the new one to the ajax response.
Realistically though, I'd imagine that you have 1 table component implementation.
What you therefore need to do, is something like this:
public class RandomNumberListModel extends LoadableDetachableModel {
private int upperBound;
public RandomNumberListModel(int upperBound) {...}
public void setUpperBound(int upperBound) {...}
protected Object load() {
// generate random number list using upper bound
// return list
}
}
...
final MyTableComponent table = new MyTableComponent(new RandomNumberListModel(30));
add(table);
AjaxLink link = new AjaxLink("myButton") {
public void onClick(final AjaxRequestTarget target) {
table.getModel().setUpperBound(100);
target.addComponent(table);
}
};
add(link);
(Edit) I've added a dynamic, reusable model to illustrate how the model would work. There are different ways of implementing this, depending on what you want to be reusable. The key point is that the model generates the list dynamically, i.e. per request, and the upperBound of the number range can be manipulated in the onClick callback.
Like jboyd was asking do you have code that knows to send the table contents back in the Ajax response?:
final Component tableComponent = ....;
AjaxLink link = new AjaxLink("myButton"){
public void onClick(final AjaxRequestTarget target) {
target.addComponent(tableComponent);
}
};
add(link);
The addComponent piece is the part jboyd is referring to.
There is one such example among the wicketstuff.org examples, the tree/tree table one. The three links at the top change the table.

The Elegant way to handle Cyclic Event in Java?

i think this not a specific problem to me; everybody might have encountered this issue before.
To properly illustrate it, here's a simple UI:
As you can see, those two spinners are controlling a single variable -- "A". The only difference is that they control it using different views.
Since these two spinners' displaying values are synchronized, cyclic event shows up.
If i change the top spinner, "A" will be changed and the bottom spinner's value will also be updated accordingly. However, updating the bottom spinner's call (such as setValue) will also trigger another event instructing the top spinner to update based on the bottom spinner's value. Thus creates a bad cycle which can eventually cause a StackOverFlow exception.
My previously solution is kinda cumbersome: i placed a guarding boolean to indicate whether the 2nd updating call should be performed.
Now i'd like to ask "how can i handle such situation elegantly? ( in general, not specific to spinners )"
thx
Update:
Since i've got 2 answers suggesting me to utilize the observer structure, i have to say something about it.
Like what i've said, it's great but far from being perfect. Not only because of its inherent complexity, but also Its inability to solve the problem.
Why? To see the reason, you must realize the tight coupling of the View and Model-Controller in Java Swing. Lets take my spinner UI for an example. Suppose the variable A is actually an Observer object. Then, after firing the first state change event from the top spinner, the Observer "A" will update its value and fire a PropertyChange event to notify the bottom spinner. Then comes the 2nd updating which updates the bottom spinner's View. However, changing bottom spinner's view inevitably triggers a redundant event that will try to set "A"'s value again. Afterwards, the deadly loop is fully constructed and the stack overflow will be thrown.
In theory, the Observer model tries to solve the direct cycle by introducing 2 independent feedback paths. The chained updating odds(in event-response codes) implicitly form a bridge connecting both paths, making a cycle again.
Going back to Model-View-Controller, think about what your Model is, and what your View is.
In your current implementation, you have two models (one for each Spinner control), and they're being synced through the View layer.
What you should be doing though is share the same backing model. For the spinner with a subtracted value, create a proxy to the original model. ie:
class ProxySpinnerModel implements SpinnerModel {
getValue() { return originalSpinner.getValue() - 10 }
setValue(v) { originalSpinner.setValue(v+10) }
}
spinnerA = new JSpinner()
spinnerB = new JSpinner( new ProxySpinnerModel( spinnerA.getModel() ) )
Now, you don't need to add listeners, since they're both working off the same model and the default implementation (the originalModel) already has change listeners which it fires to the view.
Problem Solved
I've got many different suggestions. Particularly,
i want to thank Marc W & Reverend Gonzo. I'm here to make a summary for these ideas; this can save your time navigating thru big chunk of texts.
This problem can be easily bypassed if you carefully decouple the View and Model-Controller.
The dead cycle is caused by dependent writes: write_1 -> write_2 -> write_1 ->.... Intuitively, breaking the dependency can solve the problem elegantly.
If we look into the problem in depth, we can find updating the corresponding views doesn't necessarily involves an external write call. Actually, a view only depends on the data it's representing. Known this, we can then re-write the logic as follow: write_1 -> read_2 & write_2 -> read_1.
To illustrate this idea, lets compare the 3 methods mentioned by different posters:
alt text http://www.freeimagehosting.net/uploads/2707f1b483.png
As you can see, only the proxied view can solve all the dependency thus it's the generic solution for this knid of problem.
In practice, it can be implemented as something like this (in your event-response codes):
setValue(newValue);
anotherSyncUI.parse(); // not anotherSyncUI.setValue() any more
anotherSyncUI.repaint();
No more loops. Solved.
It's a bit complicated, but you could make A actually be an object that's observable. Both spinners (or whatever needs to update itself based on A's value) would then observe A. Whenever A changes, the spinners (or again, whatever object) update themselves to reflect the new value of A. This decouples the spinners' logic from one another. In your example here, the spinners should not be coupled to one another because they really have nothing to do with each other. Instead, they should both simply be bound to A and take care of their own view updating individually.
Whenever the value in the first spinner is changed, you would simply update A's value to match it. Whenever the value in the second spinner is changed, you would of course add 10 to its value before assigning it to A.
Update
In response to the update to your original question, my answer is that the spinners do not listen to one another's change events. Have a separate event handling method for each spinner. A user clicking the up or down arrows in the spinner generates a different event than calling setValue on the spinner programmatically, correct? If the spinners are completely independent of one another, there will be no infinite loop.
E.g. for the second spinner, calculate A-10 and then compare it to the current value of the spinner. If it's the same, do nothing, ending the infinite loop. Similarly for the first spinner.
I think there are also ways to update the spinner's model in a way that doesn't fire an event, but I don't know them off the top of my head.
Use a single SpinnerModel for both JSpinners. See the following code:
Note that the call to setValue() is only made once each time a new value is defined by one of the JSpinners.
import java.awt.BorderLayout;
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JFrame jf = new JFrame();
SpinnerModel spinModel = new MySpinnerModel();
JSpinner jspin1 = new JSpinner(spinModel);
JSpinner jspin2 = new JSpinner(spinModel);
jf.setLayout(new BorderLayout());
jf.add(jspin1, BorderLayout.NORTH);
jf.add(jspin2, BorderLayout.SOUTH);
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(3);
}
}
class MySpinnerModel extends AbstractSpinnerModel {
private int _value = 0;
private int _min = 0;
private int _max = 10;
#Override
public Object getNextValue() {
if (_value == _max) {
return null;
}
return _value + 1;
}
#Override
public Object getPreviousValue() {
if (_value == _min) {
return null;
}
return _value - 1;
}
#Override
public Object getValue() {
return _value;
}
#Override
public void setValue(Object value) {
System.out.println("setValue(" + value + ")");
if (value instanceof Integer) {
_value = (Integer) value;
fireStateChanged();
}
}
}
It seems you're really observing the wrong thing. From the example given I presume what you want to detect is the user's actions on the controls, not the changes in the values themselves. As you've outlined, changes in your model are reflected in the values of the spinners, and it is this which forms the infinite loop of events.
However, diving further into the UI implementation may not be the answer you want. In that case I'd say the best you can do is either your current guard solution, or to better extract the logic into your model (similar to what Marc and William have said). How that can be done will depend on the 'real world' model behind a particular implementation of the provided puzzle.
As a rule, your model should not be defined by your GUI. Ie, the SpinnerModel that backs each JSpinner should not be your value A. (That would be a horribly inelegant tightly coupled dependency on a particular view.)
Instead, your value A should either be a POJO or a property of an object. In which case, you can add PropertyChangeSupport to it. (And presumably have already done so in any case, as you want your spinners to update automatically if A is changed by other parts of your program).
I realise this is similar to Marc W's answer, and you were concerned that it's "complicated", but PropertyChangeSupport does almost all of it for you.
In fact, for trivially simple cases, you can just use a single class that wires a "setProperty" method through to a "firePropertyChange" call (as well as storing the value in a HashMap for any "getProperty" calls).
I don't really want to solve your problem but I find it interesting. I have already been confront to it and solved it each time a different way. But when I think about the 'why ?' and not about the 'how ?' am staying perplexed.
This problem only exists because I am using an automatism (MVC) which had to help me, and exactly in that way. The art how the components are used make this automatism a barrier to a beautiful code.
Why do set #setEvent() has to produce the same event as a GUI action?
Though, my opinion is also pretty close to Observer pattern but it is a bit lighter than that!!!
Have A as a variable with a setter
private Integer A;
setA(int A)
{
this.A = A;
refreshSpinners();
}
refreshSpinners()
{
setSpinnerA();
setSpinnerAMinus10();
}
setSpinnerA()
{
// show value of A
}
setSpinnerAMinus10()
{
// show value of A-10
}

Categories

Resources