How can i disable a button when the model is not updated? - java

In my UI i have 2 text field and and 2 buttons .I am using jface data binding to bind the text field and i am doing the validation and depending on the validation success the model is updated other wise it will not.I want my button to respond accordingly .Like if my model is not updated than i want to disable my button.One more thing that i do anot want to do hard coding .so is there any way to that without hard coding.
In other way I want to bind a button to text field so that when the text field has some unwanted value than the button should be disabled .In the other way i am doing data binding on text field which will take care when the text field does not have proper value than it will not update its model.Then i want to disable the button when the value is not proper can i do that.Any pointer on this helps me a lot.

You can make use of below listener. Add listener to your Observable
org.eclipse.core.databinding.observable.value.IValueChangeListener

After some research, I found that I have to observe the enable/disable property of the button and bind it with the current emf databinding context. Detail of the function which I have used is given below:
void bindEnablementButtonToValidationStatus(Button button, EMFDataBindingContext ctx) {
IObservableValue buttonEnable = SWTObservables.observeEnabled(button);
IObservableValue validationStatus = new AggregateValidationStatus(
ctx.getValidationRealm(),
ctx.getBindings(),
AggregateValidationStatus.MAX_SEVERITY);
ctx.bindValue(buttonEnable, validationStatus,
new EMFUpdateValueStrategy(
UpdateValueStrategy.POLICY_NEVER),
new EMFUpdateValueStrategy().setConverter(
new Converter(IStatus.class, Boolean.TYPE) {
public Object convert(Object fromObject) {
return new Boolean(((IStatus)fromObject).isOK());
}
}));
}

Related

vaadin CheckBoxGroup does not render

My program can add or update profiles. In the update profile dialog, after selecting which profile u want to update. Fields should fill with selected profile values. The problem starts with filling the CheckboxGroup field. (My CheckboxGroup field name is listBox so after that I'm gonna call it that way). when I check my listBox selected items I can see the listBox selected values are true but in the frontend, I can't see any selection. So basically I want to reselect lists in addValueChangeListener but CheckboxGroup not rerendering.
listBox = new CheckboxGroup<>();
listBox.setItemLabelGenerator(Lists::getListName);
listBox.setItems();
listBox.setItems(listsList);
listBox.addThemeVariants(CheckboxGroupVariant.LUMO_VERTICAL);
listBox.setHeight("200px");
listBox.getStyle().set("overflow","AUTO");
listBox.setHelperText("Seçilen Listeler");
listBox.addThemeVariants(CheckboxGroupVariant.LUMO_HELPER_ABOVE_FIELD);
updateProfile.addValueChangeListener(e -> {
setUpdateProfileValues();
});
}
private void setUpdateProfileValues() {
if (updateProfile.getValue() == null)
return;
updateProfileName.setValue(updateProfile.getValue().getProfileName());
simAlgorithm.setValue(updateProfile.getValue().getSimAlgorithm());
searchType.setValue(updateProfile.getValue().getSearchType());
operationType.setValue(updateProfile.getValue().getOperatorType());
simPercentage.setValue(updateProfile.getValue().getSimPercentage());
numberOfResult.setValue(updateProfile.getValue().getNumberOfResults());
List<Lists> selectedLists = updateProfile.getValue().getLists();
selectedLists.forEach(lists -> log.error(lists.getListName()));
//selectedLists.forEach(listBox::select);
listBox.setValue(new HashSet<>(selectedLists));
listBox.getSelectedItems().forEach(selectedList -> log.error(selectedList.getListName()));
}
Here is my related code piece for this question. BTW when I check the logs I can see listBox has true selected values. But I need to show on frontend page.
I ran a quick piece of code using your listBox initialization and I was able to set all of the Checkboxes to true on the front end. This might help you:
listBox.getChildren().filter(Checkbox.class::isInstance)
.map(Checkbox.class::cast)
.forEach(c -> c.setValue(true));
This retrieves all the Checkboxes within the CheckboxGroup, checks that they are an instance of the Vaadin Checkbox component, and then sets their T/F value as desired.

How enable or disable correctly an Action

i have a little problem when i try to disable an Action of my Netbeans platform project. When the app starts, some Actions must be disabled, and i do that with this method:
CallableSystemAction.get(BuildProjectAction.class).setEnabled(FLAG);
It works, because the BuildProjectAction is disabled, but the corresponding items of the MenuBar and the Toolbar remains enabled until i click on one of it.
Only later that i have clicked on it, the comportament start to work correctly.
First question: Why?
If i want disable an Action, it's obvious that i want disable also the relative Icon in the Menu and in the Toolbar, so it must be automatic when i call Action.setEnabled(false).
It doesn't have sense that the Icons are not refreshed if i don't click on they.
Same problem if i try to use .getToolbarPresenter().setEnabled(false); and .getMenuPresenter().setEnabled(false);
For start the application with the icons disabled, I have tried to set the lazy attribute to FALSE and declare the image programmatically with the method setIcon(new ImageIcon(image)); that sets the same image for Menu and Toolbar.
And it works; there is only another problem: Menu and Toolbar have icons of different size (16x16 and 24x24).
It doesn't have sense that the if i set the icon with the #ActionRegistration(iconBase = "image.png") the correct icon is automatically selected, but if i use the method .setIcon(), it doesn't.
I have read some articles about Action, CookieAction, Lookup, but the only thing that i want is disable the graphic elements in the same moment when i disable the Action.
Second question: How i can do that?
This is an example of my Action.
#ActionID(
category = "Run",
id = "BuildProjectAction")
#ActionRegistration(
lazy = true,
iconBase = "images/icons/compile.png",
displayName = "#CTL_BuildProjectAction")
#ActionReferences({
#ActionReference(
path = "Menu/Run",
position = 3),
#ActionReference(path = "Toolbars/Run",
position = 3),
#ActionReference(
path = "Shortcuts",
name = "D-B")
})
#Messages("CTL_BuildProjectAction=Build Project")
public final class BuildProjectAction extends CallableSystemAction {
#Override
public void actionPerformed(ActionEvent e) {...}
#Override
public void performAction() {}
#Override
public String getName() {
return Bundle.CTL_BuildProjectAction();
}
#Override
public HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
Thanks
The easiest way to create an action that is disabled at startup is to use the platform’s New Action Wizard to create your action, and to create one that depends on a "context" -- this is, on finding a specific object in the global lookup. If no object is available in the lookup, as at startup, then the action will be disabled.
The menu and toolbar graphic elements are bundled together with your action via the annotations. This means that enabled/disabled state of your context-aware action will automatically affect the icons in the menu and toolbar as well.
This article by Geertjan Wielenga has a walkthrough on creating a context-aware action:
http://netbeans.dzone.com/how-to-make-context-sensitive-actions
When you want to enable your action, you will add the object on which the action depends into the global lookup, which will cause the action (and its graphic elements) to be enabled.
This entry in the platform’s Developer FAQ has some examples of how to add an object to the global context:
http://wiki.netbeans.org/DevFaqAddGlobalContext
If you need to create an action that depends on a more complex set of conditions there is some discussion, as well as a code sample illustrating how to do this, in this platform developer list thread:
http://forums.netbeans.org/ptopic55295.html
The grayed-out versions of the icons that are shown when your action is disabled are created automatically by the platform. You only have to provide the "normal" non-grayed-out images.
As for the icons of different sizes, it’s a matter of filename convention. If your annotation declares the icon with #ActionRegistration(iconBase = "image.png”), then you will provide a 16x16 image called “image.png” and a 24x24 version called “image24.png”. The platform will find and use the appropriate size in the menu and toolbar.

Eclipse 4 RCP Editor using SourceViewer Undo and Redo operations are not working

I'm creating an editor using 'SourceViewer'. Given below is the code snippet from my '#PostConstruct' method.
// viewer is my SourceViewer instance
viewer = new SourceViewer(parent,verticalRuler, styles);
IUndoManager undoManager = new TextViewerUndoManager(25);
undoManager.connect(viewer);
viewer.setUndoManager(undoManager);
Even though a default 'TextViewerUndoManager' associated with 'SourceViewer'. Ctrl+Z and Ctrl+Y is not working.
Another alternative that I tried is to override the 'IUndoManager getUndoManager(ISourceViewer sourceViewer)' of 'SourceViewerConfiguration' subclass and return a 'TextViewerUndoManager'. This approach also doesn't give the desired result.
Kindly let me know what I'm missing in the above approaches.
It is normally the SourceViewerConfiguration that provides the Undo manager, the SourceViewer expects this and will set up the manager from that. The defaults already set up TextViewerUndoManager.
In an e4 application you do not get any default key bindings, commands or handlers so you will have to set up all these to make use of the undo manager.
In your application model declare Commands for undo and redo.
Declare key bindings for Ctrl+Z and Ctrl+Y specifying your commands. You might want to put the key bindings in a Binding Table that is specific to text editors.
Declare Handlers for the undo and redo commands, the code for undo might look like:
public class UndoHandler
{
#Inject
private Adapter _adapter;
#Execute
public void execute(#Named(IServiceConstants.ACTIVE_PART) final MPart part)
{
final ITextOperationTarget opTarget = _adapter.adapt(part.getObject(), ITextOperationTarget.class);
opTarget.doOperation(ITextOperationTarget.UNDO);
}
#CanExecute
public boolean canExecute(#Named(IServiceConstants.ACTIVE_PART) final MPart part)
{
final ITextOperationTarget opTarget = _adapter.adapt(part.getObject(), ITextOperationTarget.class);
if (opTarget == null)
return false;
return opTarget.canDoOperation(ITextOperationTarget.UNDO);
}
}
Redo would be similar but using ITextOperationTarget.REDO.
The order of doing/registering things is important. Be sure to connect the undo manager AFTER setting the document to the SourceViewer instance because on connect() the document will be retrieved from the viewer by the undo manager and if it doesn't find a document it will not register anything and undoable() will always return false.

Custom Zk Combobox

as seen in:
http://www.zkoss.org/zkdemo/combobox/simple_combobox
When the item is selected only text appears.
How can I make the image + name appear when the item is selected?
which method from Combobox do i need to override?
ty
There is no build-in way for you to do things like that. Because a Combobox is just a textbox with a customizable drop-down list.
But this can be done pretty easily. You can just add an Image at left of the combobox, and listen combobox Events.ON_SELECT event. Then update the Image according to selected item.
Here is an example code (assuming use SelectorComposer)
#Listen("onSelect = combobox#mycmb")
public void onComboboxSelected(SelectEvent event) {
Set<MyObject> selectedObjects = event.getSelectedObjects();
MyObject obj = selectedObjects.get(0);
image.setSrc(getImagePath(obj)); // image are Image component you wired.
}
Note : I didn't test the code, but you should get the idea

Disabling Selection with CellList

I have a CellList:
friendCellList = new CellList<PlayerDataEntity>(new PlayerCell());
friendCellList.setSelectionModel(new NoSelectionModel<PlayerDataEntity>());
I am hoping that passing the NoSelectionModel will prevent the UI from reacting to the user selecting items in the cell list. However, the user is able to select elements normally. Am I not applying the selection model correctly?
From the Javadoc of NoSelectionModel:
A selection model that does not allow selection, but fires selection change
events. Use this model if you want to know when a user selects an item, but
do not want the view to update based on the selection.
That's what it does: In the Standard theme, this will result in the row not being highlighted in blue anymore ("cellListSelectedItem" style class). However, it will still be highlighted in yellow ("cellListKeyboardSelectedItem" style class). Also, the SelectionChangeEvent will still be fired.
To turn off the SelectionChangeEvent, use
cellList.setSelectionModel(new NoSelectionModel<String>(),
DefaultSelectionEventManager.<PlayerDataEntity>createWhitelistManager());
The whitelist manager without arguments means, that you can't select any column.
If you also want to turn off the "yellow" highlighting, you should instantiate CellList with a different CellList.Resources instance:
public interface MyResources extends CellList.Resources {
#Override
#Source("com/mypackage/my.css")
Style cellListStyle();
}
...
friendCellList = new CellList<PlayerDataEntity>(new PlayerCell(),
(MyResources) GWT.create(MyResources.class);
my.css:
.cellListEvenItem {}
.cellListKeyboardSelectedItem {}
.cellListOddItem {}
.cellListSelectedItem {}
.cellListWidget {}

Categories