Using Custom Swing Components

With the javafx.ext.swing package developers can easily use the standard Swing components in their JavaFX applications. However, at present this package doesn't cover all Swing components. For example, you may want to embed your own custom component.

Luckily, this is easy done with only a few lines of code. The basic approach is as follows:

  • Create a wrapper class that extends the javafx.ext.swing.SwingComponent class.

  • Override the createJComponent method, so that it creates the necessary component.

  • If you need to handle events from your component, perform the following steps:

    • Define a variable of the function type. This variable will receive events from the component.

    • Create and register Swing event listeners that delegate event handling to the specified function.

To illustrate this approach, consider the task of creating a button based on the javax.swing.JButton component. The goal is to update the text label for the button and handle events from it.

The wrapper class for the button appears as follows:

Source Code
class ButtonWrapper extends SwingComponent {
    var button: JButton;
  
    override function createJComponent() {
	    button = new JButton();
		button.addActionListener(
        ActionListener {
            public override function actionPerformed(event) {
                action();
            }
        });
		 
		button
    }
		  
    public var text: String on replace {
			button.setText(text);
	}
		
    public var action: function();
}

Using wrapper classes for the Swing components is pretty much the same as using other objects in JavaFX:

Source Code
var text = "PRESS ME";
...

content: ButtonWrapper {
  text: bind text
  action: function() {
    text = "PRESSED"
  }
}

Refer to the ExercisingSwing demo and JavaFX wiki for more information about using Swing components in JavaFX.