Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Wednesday, August 23, 2017

Setting the Pivot Point in a JavaFX ScaleTransition

This article shows how to use a JavaFX ScaleTransition to expand a container of controls from nothing to its full dimensions.  While this is especially easy to do if you are content to scale the container outward from the center, an extra transformation is needed to expand the container from the top left, in this case next to the originating control.

When working with animations, I like to use the transformations as much as possible over object properties like width and height.  That helps to preserve the integrity of the layout.  For example, a zero-width Node might cause other items to shift undesirably.  If keeping unaffected Nodes in their original place is important, prefer ScaleTransition to animating width and height and prefer TranslateTransition to x and y.

Sliding Content In With JavaFX TranslateY

A reader asked about sliding content into a screen via animation.  This blog post uses a Pane to show a slide which is animated in using the slide's translateY property. I used a Pane because it does not attempt to resize the child's contents.


Tuesday, August 1, 2017

Wire Level REST Request Logging in TornadoFX

TornadoFX's Rest class integrates RESTful web service calls into your JavaFX app.  There is a switch you can set that will allow you to use the Apache HTTPClient in place of the native Kotlin implementaton typically used in TornadoFX.  One feature that this switch brings is wire-level logging.


Friday, July 14, 2017

Op Amp Frequency Response for Bass Guitar Effects

This is a comparison of the frequency response of the OPA2132 and LM358N operational amplifiers.  These are two ICs that vary widly in price.  The OPA2132 is $6 while the LM358N is $0.40.  Both chips each contain a pair of op amps.  A few screenshots visually showing some differences is followed up by a pair of bass guitar effect circuits that highlight some audio application differences.


Tuesday, May 30, 2017

JavaFX Image Error Handling

ImageView is a JavaFX node that contains an Image.  When working with a classpath resource, an error is thrown immediately if an Image resource is not found.  However, you need to have the background flag set if your Image source is an absolute URL.

The following code will throw an exception if the resource is not on the classpath

        Image badImage = new Image("images/NOTFOUND.png");

A stack trace will look something like this

Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1110)
... 11 more

Similar code using an absolute URL will fail without throwing an error.  If using an ImageView, this results in either a blank area where the images should be shown or nothing, depending on the container.


Wednesday, April 26, 2017

Kotlin RadioButtons and Enumerated Types in TornadoFX

A previous post showed how to create a JavaFX property based on an Enum linked to a set of RadioButtons.  Selecting a RadioButton changed the Enum property.  Changing the Enum property selected (and de-selected) a RadioButton.  This Kotlin code shows a recent enhancement in  TornadoFX 1.7.4 which wraps this functionality up using an extension function.

An example usage of this new function follows.


Tuesday, April 25, 2017

JavaFX RadioButtons and Enumerated Types

In JavaFX, RadioButtons are usually added to a ToggleGroup to make the selections mutually exclusive.  The RadioButton selection can be bound as a property to another BooleanProperty field.  That pairing also supports bindBidirectional() such that the RadioButton control can update the field and the field can update the control.

You may want to bind the RadioButton selection to an enumerated type.  Say, you have an enumeration ChoiceType with 3 values.  You want to map each of those 3 values to a RadioButton.  Moreover, you'd like to maintain a single field of ChoiceType for use in a model component.


Monday, March 27, 2017

Kotlin Elements in TorandoFX Type Safe Builders

While the Kotlin-based TornadoFX framework supports many styles to construct a JavaFX UI, the Type Safe Builders are preferred.  Borrowing from a popular Groovy syntax, the TornadoFX Type Safe Builders are Kotlin Extension Functions that use Lambdas to write cleaner programs.

This is an example TornadoFX View which is an HBox containing three Labels.

class GridDemosMainView : View() {

    override val root = hbox {

        label("Label 1")
        label("Label 2")
        label("Label 3")
    }
}

Monday, January 16, 2017

C# WebClient Parsing JSON Array

This is a snippet of code that calls a RESTful web service and parses the JSON result.  The JSON payload is a list of objects.  The solution uses the .NET class DataContractJsonSerializer and an annotated DataContract.

Saturday, December 3, 2016

Kotlin Callable Reference Notes

Method references were added to Java 8 and you may already be using the double-colon (::) syntax to use a method reference as a parameter.  The semantics in Kotlin are different although a change in 1.1 will address these differences.

This article presents a few examples of passing function references in Kotlin 1.0.

Sunday, November 6, 2016

Securing JavaFX Content Based on Role

This is an example where a MainView contains two child views, AllAccessView and AdminOnlyView.  All of the views are in .fxml and AllAccessView and AdminOnlyView are fx:included in MainView.

A setRole() method is provided by MainViewController.  This method sets an internal field which is tied to a ChangeListener.  The ChangeListener will decide, based on role, whether or not to show both views (for Admin) or just one (for User).

The fx:include code is wrapped up in Boxes to make the adding and removing easier.

I'll expand upon this later.

The code will explain things better.

SecuredApp Source

Monday, October 24, 2016

Disambiguiating Nil Arguments in Swift

Overloading functions in Swift enables you to use the same function name with arguments of different types.  This can lead to an easier-to-use API, especially with code completion.  Instead of having a complement of functions like

  saveMyClass(myclass)
  saveAnotherClass(anotherclass), and
  saveYetAnotherClass(yetanotherclass),

you'd just use a single save() function that would accept the three different types.  The previous example becomes

  save(myclass),
  save(anotherclass), and
  save(yetanotherclass).


Disambiguating Null Arguments in Kotlin

To define a function argument that can accept a null value in Kotlin, you use the question mark (?) operator.  For example,

fun bar(name : String?) { // ... do something

Can accept both a String argument like "Hello, World!" and a null.  If you have another version of bar() that accepts a nullable argument, say

fun bar(name : Int?) { // ... do something w. an Int

You'll run into a problem if you call

bar(null)

To disambiguate this, you need to provide type into to Kotlin. That type info should be a nullable type. In the following code, a method "foo" is updated with a newer version. Both functions can coexist when non-null arguments are passed. The Kotlin as keyword is used to specify exactly which function is to be used for the null value (and the code compiled).


Wednesday, September 21, 2016

A TornadoFX Kotlin Context Menu with Alert Confirmation

This post demonstrates how to specify an action handler for the TornadoFX alert() function.  This code supports a ContextMenu delete operation.  The delete operation requires a confirmation.   "Cancel" will cancel the delete operation, closing the ContextMenu.  "OK" will adjust the TableView and call the back-end logic through a TornadoFX Controller class.

The purpose of the post is to show the syntax of Kotlin and TornadoFX rather than provide working code.  For that type of tutorial, check out courses.bekwam.net/public_tutorials.


Monday, September 19, 2016

Thursday, September 15, 2016

Wednesday, September 14, 2016

Visual Cues Through JavaFX ChangeListeners

This is the third post in a series on confirming input using JavaFX.  The prior posts demonstrated how to control access to a Save Button and how to integrate a Commons Validator object to validate an email  This post adds a visual cue to the program that guides the user into producing correct input.  A ChangeListener is applied to a custom BooleanBinding which is triggered when the input is changed.

Also, an animation is applied to smooth the display of the visual cue.

Tuesday, September 13, 2016

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is used to apply the email validation rules to a TextField.  This is hooked in to the JavaFX program using a compound Binding expression.


Disabling a Save Button with JavaFX Confirmation Binding Controls

This post demonstrates a one-line JavaFX Binding expression that disables a Save Button until a confirmed input is entered into a pair of TextFields.

btnSave.disableProperty().bind(
    txtEmail.textProperty().isEqualTo(txtConfirmEmail.textProperty()).not()
    .or(
        txtEmail.textProperty().isEmpty()
    )
);

Thursday, September 8, 2016

Rewriting Nested Loops as Java Streams

This post rewrites a nested loop as a pair of Java Streams.  While there isn't much savings in comparing each statement in isolation, there will be more value if the first Stream's output is retained for other logic.  For example, if there are several blocks of code that need "activeRolesIds", then it's worthwhile to factor out that code in a Stream.

This statement sets one or more ToggleButton to selected if that ToggleButton's userData is found in the activeRoles list which is returned from the JavaFX ListProperty roles.getValue().

       
for( RoleDTO activeRole : roles.getValue() ) {
    for( Node availableRoleNode : hboxRoles.getChildren() ) {
        if( availableRoleNode.getUserData().equals( activeRole.getRoleId() ) ) {
            ( (ToggleButton) availableRoleNode ).setSelected( true );
            break;
            }
        }
}

This can be replaced with two Streams.  The first Stream maps a List of Integer values that is used in the second Stream's filter predicate.

List<Integer> activeRoleIds = roles.getValue()
    .stream()
    .map( (r) -> r.getRoleId() )
    .collect(Collectors.toList());

hboxRoles.getChildren()
    .stream()
    .filter( (n) -> activeRoleIds.contains(n.getUserData()) )
    .forEach( (n) -> ((ToggleButton)n).setSelected(true) );

Both the nested loops and the pair of Streams will set the appropriate ToggleButton state.  The Streams versions will offer a savings if later blocks of code also can use the activeRoleIds List.

Update

Here's another example of a loop (not a nested loop) rewritten as a Lambda.

hboxRoles.getChildren().clear();
for( RoleDTO role : availableRoles ) {
    ToggleButton tb = new ToggleButton( role.getRoleName() );
    tb.setUserData( role.getRoleId() );
    hboxRoles.getChildren().add( tb );
}

The Lambda uses the map() method to convert transfer objects (RoleDTO) into JavaFX controls (ToggleButton).

hboxRoles.getChildren().setAll(

    availableRoles
        .stream()
        .map( (r) ->l; {
            ToggleButton tb = new ToggleButton(r.getRoleName());
            tb.setUserData( r.getRoleId() );
            return tb;
        })
        .collect(Collectors.toList())

);