In JavaFX 8 how can I bind to a computed expression? - javafx-8

I apologize if this is a repeat (couldn't find one) or pretty simple. I just can't find anything on it.
I would like to have a dynamic title on my primary stage based on values in a table. However I can't seem to find a way to handle this without have to code it on an event listener. I'd rather create a binding if possible.
Something like this:
primaryStage.titleProperty().bind("Open Items" + tableView.getItems().size());

primaryStage.titleProperty().bind(Bindings.size(tableView.getItems()).asString("Open Items %d"));
or
primaryStage.titleProperty().bind(Bindings.createStringBinding(() ->
"Open Items "+tableView.getItems().size(),
tableView.getItems());
or
primaryStage.titleProperty().bind(new StringBinding() {
{ bind(tableView.getItems()); }
#Override
public String computeValue() {
return "Open Items "+tableView.getItems().size();
}
});
and probably many other ways...

Related

Flutter 1.22 Internationalization with variable as key

I implemented the new (official) localization for Flutter (https://pascalw.me/blog/2020/10/02/flutter-1.22-internationalization.html) and everything is working fine, except that I don't know how to get the translation for a variable key.
The translation is in the ARB file, but how can I access it?
Normally I access translations using Translations.of(context).formsBack, but now I would like to get the translation of value["labels"]["label"].
Something like Translations.of(context).(value["labels"]["label"]) does not work of course.
I don't think this is possible with gen_l10n. The code that is generated by gen_l10n looks like this (somewhat abbreviated):
/// The translations for English (`en`).
class TranslationsEn extends Translations {
TranslationsEn([String locale = 'en']) : super(locale);
#override
String get confirmDialogBtnOk => 'Yes';
#override
String get confirmDialogBtnCancel => 'No';
}
As you can see it doesn't generate any code to perform a dynamic lookup.
For most cases code generation like this is a nice advantage since you get auto completion and type safety, but it does mean it's more difficult to accommodate these kinds of dynamic use cases.
The only thing you can do is manually write a lookup table, or choose another i18n solution that does support dynamic lookups.
A lookup table could look something like this. Just make sure you always pass in the current build context, so the l10n code can lookup the current locale.
class DynamicTranslations {
String get(BuildContext context, String messageId) {
switch(messageId) {
case 'confirmDialogBtnOk':
return Translations.of(context).confirmDialogBtnOk;
case 'confirmDialogBtnCancel':
return Translations.of(context).confirmDialogBtnCancel;
default:
throw Exception('Unknown message: $messageId');
}
}
}
To provide an example for https://stackoverflow.com/users/5638943/kristi-jorgji 's answer (which works fine):
app_en.arb ->
{
"languages": "{\"en\": \"English\", \"ro\": \"Romanian\"}"
}
localization_controller.dart ->
String getLocaleName(BuildContext ctx, String languageCode) {
return jsonDecode(AppLocalizations.of(ctx)!.languages)[languageCode];
}
getLocaleName(context, 'ro') -> "Romanian"
You can store a key in translation as json string.
Then you read it, parse it to Map<string,string> and access dynamically what you need.
Been using this approach with great success

How to make basic bindings in ReactiveCocoa 3 and 4

I've been reading up on ReactiveCocoa v3 lately and I'm struggling with just setting up basic stuff. I've already read the changelog, the tests, the few SO questions and the articles by Colin Eberhardt on the subject. However, I'm still missing examples on basic bindings.
Let's say I have an app that presents the menu of the day. The app is using RAC3 and the MVVM pattern.
Model (Menu)
The model has one simple method for fetching todays menu. As for now, this don't do any network requests, it basically just creates a model object. The mainCourse property is a String.
class func fetchTodaysMenu() -> SignalProducer<Menu, NoError> {
return SignalProducer {
sink, dispoable in
let newMenu = Menu()
newMenu.mainCourse = "Some meat"
sendNext(sink, newMenu)
sendCompleted(sink)
}
}
ViewModel (MenuViewModel)
The view model exposes different String variables for letting the view controller show the menu. Let's just add one property for showing the main course.
var mainCourse = MutableProperty("")
And we add a binding for this property:
self.mainCourse <~ Menu.fetchTodaysMenu()
|> map { menu in
return menu.mainCourse!
}
ViewController (MenuViewController)
Last but not least, I want to present this main course in a view. I'll add a UILabel for this.
var headline = UILabel()
And finally I want to set the text property of that UILabel by observing my view model. Something like:
self.headline.text <~ viewModel.headline.producer
Which unfortunately does not work.
Questions
The method fetchTodaysMenu() returns a SignalProducer<Menu, NoError>, but what if I want this method to return a SignalProducer<Menu, NSError> instead? This would make my binding in my view model fail as the method now may return an error. How do I handle this?
As mentioned, the current binding in my view controller does not work. I've been playing around with creating a MutableProperty that represents the text property of the UILabel, but I never got it right. I also think it feels clumsy or verbose to have to create extra variables for each property I want to bind. This was not needed in RAC2. I intentionally also tried to avoid using DynamicProperty, but maybe I shouldn't? I basically just want to find the right way of doing RAC(self.headline, text) = RACObserve(self.viewModel, mainCourse);.
Any other feedback/guidance on how to make this basic setup is highly appreciated.
So, after writing this question Colin Eberhardt made a part 3 of his RAC3 blog post series which includes a interesting and very relevant example of using MVVM and RAC3. The post can be found here and the source code here.
Based on his work, I've managed to answer my own questions:
By taking a slightly different approach, I'm able to make the fetchTodaysMenu() return a SignalProducer<Menu, NSError> as wanted. Here's how what I then would do in my view model:
MenuService.fetchTodaysMenu()
|> observeOn(QueueScheduler.mainQueueScheduler)
|> start(next: { response in
self.mainCourse.put(response.mainCourse!)
}, error: {
println("Error \($0)")
})
It seems like there's no UIKit bindings yet as of RAC3 beta 4. Colin made some UIKit extensions himself to help him make these bindings I was looking for as well. These can be found here. Adding them to my project, made be able to do exactly what I wanted to:
self.mainCourse.rac_text <~ self.viewModel.mainCourse
Update May 25, 2015
After been working a lot more with ReactiveCocoa 3, I would like to answer 1) once again. By using catch, it's possible to do this in a more declarative manner. I ended up implementing a small helper function for this:
public func ignoreError<T: Any, E: ErrorType>(signalProducer: SignalProducer<T, E>) -> SignalProducer<T, NoError> {
return signalProducer
|> catch { _ in
SignalProducer<T, NoError>.empty
}
}
The function transforms any NSError to NoError making it possible to bind as I wanted to by doing MenuService.fetchTodaysMenu() |> ignoreError.
I open sourced my project as this might be a good starting point for others looking into ReactiveCocoa 3.0:
https://github.com/s0mmer/TodaysReactiveMenu
Update March 5, 2016
As highlighted in the comments, since Swift 2, the ignoreError function would now look like:
public func ignoreError() -> SignalProducer<Value, NoError> {
return flatMapError { _ in
SignalProducer<Value, NoError>.empty
}
}
Also, an extension library called Rex has also been made, where something similar has been added.

In Tritium, is there a way to assign an id based on child number?

I have a table with a series of rows. I want to change them into divs, but maintain (somehow) their positional information. At the moment, this is what I'm doing:
$("./tr[1]") {
add_class("mw_old_row_1")
}
$("./tr[2]") {
add_class("mw_old_row_2")
}
$("./tr") {
name("div")
}
But this isn't ideal because:
It's super-repetitive
I don't know how many rows there are
Is there a way to take the child number and include that in the class I'm assigning?
Yup, you want to make use of the index() function. Below is the example you wrote reworked using index():
$("./tr") {
add_class("mw_old_row_" + index())
name("div")
}
Below is a link with the following example in tritium tester: http://tester.tritium.io/775895b154e8e2ce99e100967299c10d73dbeb91

How to name a Class for container of resulted items of a clicked item?

I have an item X that when clicked will be splitted into 1 or more items.
So I have an ArrayList that will be returning the items but I am not sure of how to name the class of that ArrayList.
the class will hold itemName and Count.
public class WhatNameShouldItBe
{
public int itemId ...;
public int itemCount ...;
}
ArrayList<WhatNameShouldItBe> resultItems;
PS: Sorry about the question title ... if you need more information let me know was not sure if anything else was needed to such a question.
Some names I was thinking about:
ExtractedItems but since it is not extracted yet doesnt sound right to me...
ResultedItems or ResultItems
ClickableItemsResult
It is a list of items that can be given to the user when they use a clickable item
English isn't my native language, but I'll give it a shot anyway : SpawnedItem ?
You have a class describing something that has properties. Say it's a Widget. Each widget has an ID and a Count.
You then want a list of these Widgets. No problem, you make an ArrayList and name it something appropriate to what purpose the list serves:
public class Widget
{
public int itemId ...;
public int itemCount ...;
}
ArrayList<Widget> ClickedWidgets;
If the main purpose of the list is to differentiate those Widgets that were clicked on, then call it ClickedWidgets or something similar.
Remember, the most important thing about naming variables in programming is that it makes sense to you. (It also helps if others can figure it out later!)
A little bit vague on the question, but perhaps "Fragments" would work.

How to filter files when opening using NetBeans?

I'm looking for a way to filter files in an "Open" window. I'm using NetBeans IDE 6.5.
I did some research, and this is what i came up with, but for some reason it's not working.
//global variable
protected static FileFilter myfilter;
//in declaration of variables
fchoLoad.setFileFilter(myfilter);
//inside main
myfilter = .... (i actually delted this part by accident, i need to filter only .fwd files. can anybody tell me what goes here?)
If I understand it correctly, you want to create your own file chooser and be able to filter just some files (.fwd in your case). I guess this is more general Java question (not only NetBeans) and I suggest reading this tutorial
Anyway, your "myfilter" should look like this:
myfilter = new FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".fwd")
|| f.isDirectory();
}
public String getDescription() {
return "FWD Files"; //type any description you want to display
}
};
Hope that helps