How to add multiple BooleanBinding to single button? - button

I need to make multiple bindings and address them to the same button.
Right now I have this BooleanBinding:
BooleanBinding even = new BooleanBinding() {
{ super.bind(plaintextHex.textProperty()); }
#Override
protected boolean computeValue() {
return ((plaintextHex.getText().length() % 2) != 0);
}
};
And this one:
BooleanBinding maxS = new BooleanBinding() {
{ super.bind(keyHex.textProperty()); }
#Override
protected boolean computeValue() {
return (keyHex.getText().length() > 32);
}
};
If I want to assign one BooleanBinding it looks like this: crButton.disableProperty().bind(even);, but if I want to assgin muttiple I can't find any info on how to do it. The idea was that it would look something like this: crButton.disableProperty().bind(even, maxS);, but of course it doesn't work like that. Do I have to make both in the same BooleanBinding or there is a method to combine them?

Depending on exactly what you need, you can do
crButton.disableProperty().bind(even.or(maxS));
or
crButton.disableProperty().bind(even.and(maxS));
Or you can just create a single binding:
BooleanBinding maxSOrEven = new BooleanBinding() {
{ super.bind(keyHex.textProperty(), plaintextHex.textProperty()); }
#Override
protected boolean computeValue() {
return keyHex.getText().length() > 32 || plaintextHex.getText().length() % 2 != 0 ;
}
};
crButton.disableProperty().bind(maxSOrEven);
etc.

Related

Searching and highlighting in a TextArea

I have a TextArea with a text in which I want to search for word(s). The search works, but highlighting the word with selectRange() does not. Is there a different method for highlighting?
findButton.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if (textField.getText() != null && !textField.getText().isEmpty()) {
int index = textArea.getText().indexOf(textField.getText());
if (index == -1) {
errorText.setText("Search key Not in the text");
} else {
// errorText.setText("Found");
textArea.selectRange(textField.getText().charAt(0), textField.getLength());
}
} else {
errorText.setText("Missing search key");
// errorText.setFill(Color.RED);
}
}
});
Surely you mean
textArea.selectRange(index, index + textField.getLength());

How to get an auto-sorting TableView?

I have a TableView with a list of items (Transaction) and want it to sort, so that all positive values are above the negative ones. This is the only requirement.
What I have until now:
expensesTableView.sortPolicyProperty().set(
new Callback<TableView<Transaction>, Boolean>() {
#Override
public Boolean call(TableView<Transaction> param) {
Comparator<Transaction> c = (a, b) -> {
if (a.getValue().contains("-") ^ b.getValue().contains("-")) { //getValue() returns a String
return a.getValue().contains("-") ? 1 : -1;
}
return 0;
};
FXCollections.sort(expensesTableView.getItems(), c);
return true;
};
});
This wasn't my idea, I found this on the net, so don't ask if it looks like a strange way to achieve that. The real problem is, that the table doesn't sort on its own when a new item is added/edited/deleted. I need to click the header 3 times and then it does what I want.
How can I have a list that is always sorted correctly?
I tried adding a ChangeListener and sort on change. But besides that this is an ugly way to do that, it didn't even work... I'm at the end of ideas.
The bitwise OR in the comparator didn't work in my tests, so I've changed it to a normal one, and it's also not checking for change in the value of items from the list.
I wonder if it might be more efficient to do a numeric check rather than a String check, negatives could still sort out below, but I guess the conversion might cost more?
My first idea with SortedList in the comments was actually related to keeping the original sorted order, to be restored after the user has changed the sort, so was off the mark.
Edited to add: Just to clarify, it's the act of keeping the source list sorted that keeps the table list sorted.
public class TestApp extends Application {
private int c;
private ObservableList<TestTransaction> sortedOL;
private final Comparator<TestTransaction> comp = (TestTransaction a, TestTransaction b) -> {
if (a.getValue().contains("-") || b.getValue().contains("-")) {
return a.getValue().contains("-") ? 1 : -1;
}
return 0;
};
private TableView<TestTransaction> tableView;
#Override
public void start(Stage primaryStage) {
ArrayList<TestTransaction> rawList = new ArrayList<>();
for (int i = 1; i < 20; i++) {
int v = i * 3;
if (v % 2 > 0) {
v = v * -1;
}
c = i;
rawList.add(new TestTransaction(Integer.toString(v), "Item " + c));
}
sortedOL = FXCollections.observableArrayList(rawList);
sortedOL.addListener((ListChangeListener.Change<? extends TestTransaction> c1) -> {
if (c1.next() && (c1.wasAdded() || c1.wasRemoved())) {
FXCollections.sort(sortedOL, comp);
}
});
FXCollections.sort(sortedOL, comp);
tableView = new TableView<>(sortedOL);
TableColumn<TestTransaction,String> valCol = new TableColumn<>("Value");
valCol.setCellValueFactory(new PropertyValueFactory("value"));
TableColumn<TestTransaction,String> nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory("name"));
tableView.getColumns().setAll(valCol, nameCol);
BorderPane tpane = new BorderPane();
Button btnAdd = new Button("Add");
btnAdd.setOnAction(a -> {addTransaction();});
ToolBar tb = new ToolBar(btnAdd);
tpane.setTop(tb);
tpane.setCenter(tableView);
tpane.setPrefSize(600, 600);
Scene scene = new Scene(tpane, 600, 600);
primaryStage.setTitle("Test");
primaryStage.setScene(scene);
primaryStage.show();
}
private void addTransaction() {
c++;
int v = (int) Math.floor(Math.random() * 50);
if (v % 2 > 0) {
v = v * -1;
}
sortedOL.add(new TestTransaction(Integer.toString(v), "New Item " + c));
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
public class TestTransaction {
private String value;
private String name;
public TestTransaction(String value, String name) {
this.value = value;
this.name = name;
}
/**
* #return the value
*/
public String getValue() {
return value;
}
/**
* #return the name
*/
public String getName() {
return name;
}
}
If you want to use SortedList, meaning you could inline the comparator:
sortedOL = FXCollections.observableArrayList(rawList);
SortedList sorted = new SortedList(sortedOL, comp);
tableView = new TableView<>(sorted);

Spinner control value

I'm using Spinner from 8u40b17.
SpinnerValueFactory svf = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 100);
Spinner sp = new Spinner();
sp.setValueFactory(svf);
sp.setEditable(true);
sp.setPrefWidth(80);
I noticed that when I enter some value from keyboard and I increase the upper value the expected number is not the next. Instead of this it's the next default value. How I can fix this?
For example: if I have 5 as default value and I enter 34, then press the upper arrow I expect to get 35 by actually get 6.
I had the same problem with the spinner control. Your bug has been documented here: JDK-8094205
Here is the last comment:
Jonathan Giles added a comment - Dec, 15 2014 12:59 AM
Fixed locally in my repo, will push to the 8u60 repo this week once it
opens. Now the text editor input is committed when increment /
decrement are called (although the value is still not committed when
focus is lost).
Unit tests:
javafx.scene.control.SpinnerTest.test_rt_39655_decrement()
javafx.scene.control.SpinnerTest.test_rt_39655_increment()
The changeset: http://hg.openjdk.java.net/openjfx/8u-dev/rt/rev/89ca7d3f699e
Here is my take on an Autocommit spinner. This one will auto commit anything that the factory will accept.
public class SpinnerAutoCommit<T> extends Spinner<T> {
public SpinnerAutoCommit() {
super();
addListenerKeyChange();
}
public SpinnerAutoCommit(int min, int max, int initialValue) {
super(min, max, initialValue);
addListenerKeyChange();
}
public SpinnerAutoCommit(int min, int max, int initialValue, int amountToStepBy) {
super(min, max, initialValue, amountToStepBy);
addListenerKeyChange();
}
public SpinnerAutoCommit(double min, double max, double initialValue) {
super(min, max, initialValue);
addListenerKeyChange();
}
public SpinnerAutoCommit(double min, double max, double initialValue, double amountToStepBy) {
super(min, max, initialValue, amountToStepBy);
addListenerKeyChange();
}
public SpinnerAutoCommit(ObservableList<T> items) {
super(items);
addListenerKeyChange();
}
public SpinnerAutoCommit(SpinnerValueFactory<T> valueFactory) {
super(valueFactory);
addListenerKeyChange();
}
private void addListenerKeyChange() {
getEditor().textProperty().addListener((observable, oldValue, newValue) -> {
commitEditorText();
});
}
private void commitEditorText() {
if (!isEditable()) return;
String text = getEditor().getText();
SpinnerValueFactory<T> valueFactory = getValueFactory();
if (valueFactory != null) {
StringConverter<T> converter = valueFactory.getConverter();
if (converter != null) {
T value = converter.fromString(text);
valueFactory.setValue(value);
}
}
}
}
By design, the changes in the textfield of the Spinner control are commited only when the user hits ENTER key, via action handler:
getEditor().setOnAction(action -> {
String text = getEditor().getText();
SpinnerValueFactory<T> valueFactory = getValueFactory();
if (valueFactory != null) {
StringConverter<T> converter = valueFactory.getConverter();
if (converter != null) {
T value = converter.fromString(text);
valueFactory.setValue(value);
}
}
});
Note that if the typed value can't be converted, this will throw a NumberFormatException, keeping the wrong value in the textfield.
We can provide our own implementation, listening to other keys, like TAB key, via event filter, and at the same time, and in case of exception, restore the last valid value.
Something like this:
private final Spinner sp = new Spinner();
#Override
public void start(Stage primaryStage) {
SpinnerValueFactory svf = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 100);
sp.setValueFactory(svf);
sp.setEditable(true);
sp.setPrefWidth(80);
// Commit on TAB
sp.addEventFilter(KeyEvent.ANY, e->{
if (sp.isEditable() && e.getCode().equals(KeyCode.TAB)) {
doCommit();
e.consume();
}
});
// Override Commit on ENTER
sp.getEditor().setOnAction(e->{
if(sp.isEditable()) {
doCommit();
e.consume();
}
});
Scene scene = new Scene(new StackPane(sp), 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
/*
Commit new value, checking conversion to integer,
restoring old valid value in case of exception
*/
private void doCommit(){
String text = sp.getEditor().getText();
SpinnerValueFactory<Integer> valueFactory = sp.getValueFactory();
if (valueFactory != null) {
StringConverter<Integer> converter = valueFactory.getConverter();
if (converter != null) {
try{
Integer value = converter.fromString(text);
valueFactory.setValue(value);
} catch(NumberFormatException nfe){
sp.getEditor().setText(converter.toString(valueFactory.getValue()));
}
}
}
}
This solved the problem for me but it relys on Apache Commons Validator to validate entered value in the spinner (org.apache.commons.validator.GenericValidator)
valueSpinner.getEditor().textProperty().addListener((observable, oldValue, newValue) -> {
try {
if (GenericValidator.isInt(newValue)) {
valueSpinner.getValueFactory().setValue(Integer.parseInt(newValue));
}
} catch (NumberFormatException e) {
if (GenericValidator.isInt(oldValue)) {
valueSpinner.getValueFactory().setValue(Integer.parseInt(oldValue));
}
}
});
Edit :-
You can validate the value without using Apache Commons Validator like this example :-
private boolean isInteger(String value) {
if (value == null) {
return false;
}
try {
new Integer(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
valueSpinner.getEditor().textProperty().addListener((observable, oldValue, newValue) -> {
try {
if (isInteger(newValue)) {
valueSpinner.getValueFactory().setValue(Integer.parseInt(newValue));
}
} catch (NumberFormatException e) {
if (isInteger(oldValue)) {
valueSpinner.getValueFactory().setValue(Integer.parseInt(oldValue));
}
}
});

JFace button in TableViewerColumn

Is it possible to have a button in a TableViewerColumn? There are several posts that confirm this, but I've found no code that actually works. I've read about a DialogCellEditor, too, is that what to look into?
Regards,
Marcus
As this seems to be a common problem, I've tried a workaround. I use an image as label and add editing support like so:
col = createTableViewerColumn(titles[10], bounds[10], 10);
col.setEditingSupport(new DeleteSupport(viewer));
col.setLabelProvider(new ColumnLabelProvider() {
#Override
public Image getImage(Object element) {
return new Image(ApplicationRunner.getApp().getShell()
.getDisplay(), "ressources/images/delete.png");
}
#Override
public String getText(Object element) {
return "";
}
});
In the DeleteSupport class (extending EditingSupport), you have to let canEdit() return false, so the image is not selectable. But then, you can't work with getValue(). So, I do whatever I have to in canEdit() BEFORE returning false. That's the same behavior as a simple push button would have.
The DeleteSupport looks like this:
public class DeleteSupport extends EditingSupport {
private final TableViewer viewer;
public DeleteSupport(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
}
#Override
protected CellEditor getCellEditor(Object element) {
return new TextCellEditor(viewer.getTable());
}
#Override
protected boolean canEdit(Object element) {
// if confirmed, try to delete the customer
if (MessageDialog.openConfirm( ApplicationRunner.getApp().getShell(),
"Confirm delete",
"Soll " + ((Customer) element).getFirstname()
+ " " + ((Customer) element).getLastname()
+ " be deleted? Cannot be undone!")) {
try {
CustomerDAO.getInstance().delete(((Customer) element).getId());
} catch (SQLException e) {
// TODO something
}
}
// reload anyways
try {
viewer.setInput(CustomerDAO.getInstance().getAll());
} catch (SQLException e) {
// TODO something else
}
viewer.refresh();
return false;
}
#Override
protected Object getValue(Object element) {
return "";
}
#Override
protected void setValue(Object element, Object value) {
}
}

Save selected items when using caliburn.micro /Telerik RadGridView /Silverlight

I am using Caliburn micro(1.3)/MVVM and Silverlight. When I update the itemsource RadGridView, I lose the selected items. I found a blog about implementing a behavior to save the selected items when you are implementing MVVM. I can get the selected items, but I cannot set them back once the itemsource is refreshed. Can someoneshow me how to implement this using caliburn.micro and the RadGridVIew? I think the best way to go is to create a caliburn micro convention, but I can only find a reference for creating a convention for selectedItem, not selectedItems.
Can someone show me how to accomplish this? I tried the following, but it does not work.
private static void SetRadGridSelecteditemsConventions()
{
ConventionManager
.AddElementConvention<DataControl>(DataControl.ItemsSourceProperty, "SelectedItem", "SelectionChanged")
.ApplyBinding = (viewModelType, path, property, element, convention) =>
{
ConventionManager.SetBinding(viewModelType, path, property, element, convention, DataControl.ItemsSourceProperty);
if (ConventionManager.HasBinding(element, DataControl.SelectedItemProperty))
return true;
var index = path.LastIndexOf('.');
index = index == -1 ? 0 : index + 1;
var baseName = path.Substring(index);
foreach (var selectionPath in
from potentialName in ConventionManager.DerivePotentialSelectionNames(baseName)
where viewModelType.GetProperty(potentialName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) != null
select path.Replace(baseName, potentialName))
{
var binding = new Binding(selectionPath) { Mode = BindingMode.TwoWay };
BindingOperations.SetBinding(element, DataControl.SelectedItemProperty, binding);
}
return true;
};
}
Thanks,
Stephane
You should use a behavior for this since the SelectedItems property is readonly.
Telerik has an example for this, only the example is not specific for caliburn.micro.
If you add the following class to your project:
public class MultiSelectBehavior : Behavior<RadGridView>
{
public INotifyCollectionChanged SelectedItems
{
get { return (INotifyCollectionChanged)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", typeof(INotifyCollectionChanged), typeof(MultiSelectBehavior), new PropertyMetadata(OnSelectedItemsPropertyChanged));
private static void OnSelectedItemsPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
{
var collection = args.NewValue as INotifyCollectionChanged;
if (collection != null)
{
collection.CollectionChanged += ((MultiSelectBehavior)target).ContextSelectedItems_CollectionChanged;
}
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectedItems.CollectionChanged += GridSelectedItems_CollectionChanged;
}
void ContextSelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UnsubscribeFromEvents();
Transfer(SelectedItems as IList, AssociatedObject.SelectedItems);
SubscribeToEvents();
}
void GridSelectedItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
UnsubscribeFromEvents();
Transfer(AssociatedObject.SelectedItems, SelectedItems as IList);
SubscribeToEvents();
}
private void SubscribeToEvents()
{
AssociatedObject.SelectedItems.CollectionChanged += GridSelectedItems_CollectionChanged;
if (SelectedItems != null)
{
SelectedItems.CollectionChanged += ContextSelectedItems_CollectionChanged;
}
}
private void UnsubscribeFromEvents()
{
AssociatedObject.SelectedItems.CollectionChanged -= GridSelectedItems_CollectionChanged;
if (SelectedItems != null)
{
SelectedItems.CollectionChanged -= ContextSelectedItems_CollectionChanged;
}
}
public static void Transfer(IList source, IList target)
{
if (source == null || target == null)
return;
target.Clear();
foreach (var o in source)
{
target.Add(o);
}
}
}
This behavior takes care of the synchronization between collection RadGridView.SelectedItems and MultiSelectBehavior.SelectedItems.
Now we need to have an ObservableCollection in the ViewModel
//Collection holding the selected items
private ObservableCollection<object> selectedGridItems;
public ObservableCollection<object> SelectedGridItems
{
get
{
if (selectedGridItems == null)
selectedGridItems = new ObservableCollection<object>();
return selectedGridItems;
}
set
{
if (selectedGridItems == value) return;
selectedGridItems = value;
NotifyOfPropertyChange(() => SelectedGridItems);
}
}
//Deselect all selected items in the gridview
public void ClearSelectedGridItems()
{
SelectedGridItems.Clear();
}
Last thing is bind the behavior in the view
<telerik:RadGridView x:Name="CustomLogs" AutoGenerateColumns="true" SelectionMode="Extended">
<i:Interaction.Behaviors>
<local:MultiSelectBehavior SelectedItems="{Binding SelectedGridItems}"/>
</i:Interaction.Behaviors>
</telerik:RadGridView>
Thats it, hope it helps you!

Resources