Skip to main content

How to use existing JComponent in JavaFX?

4 replies [Last post]
midipig
Offline
Joined: 2004-08-13

I want to write a JavaFX GUI to wrap my existing JComponent. My existing JComponent is a JPanel that contains JSpinner, JButton and JTable. Is there an easy way to simply "add" this JComponent into JavaFX GUI? Thanks.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
alexsch
Offline
Joined: 2007-07-12

Just extend SwingComponent class:

[code]
import javax.swing.JButton;
import javax.swing.JComponent;
import javafx.ext.swing.SwingComponent;

class MySwingComponent extends SwingComponent{

var myComponent: JComponent;

public override function createJComponent():JComponent{
myComponent = new JButton("Click Me!");
return myComponent;
}

}
[/code]

gillman
Offline
Joined: 2006-06-18

Is there a way to expose the properties of the SwingComponent you are extending?

I.E.

[code]

Frame {
title: "Example", width: 600, height: 600, visible: true

stage: Stage {
content: [
MySwingComponent {
text: "Click Me!"
toolTipText: "Tool tip text"
}
]
}
}

[/code]

alexsch
Offline
Joined: 2007-07-12

> Is there a way to expose the properties of the
> SwingComponent you are extending?

Yes, there is.

[code]
import javax.swing.JButton;
import javax.swing.JComponent;
import javafx.ext.swing.SwingComponent;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class MyButtonComponent extends SwingComponent{

var button: JButton;

public var text: String on replace{
button.setText(text);
}

public var toolTipText: String on replace{
button.setToolTipText(toolTipText);
}

public var action: function();

public override function createJComponent():JComponent{
button = new JButton();
button.addActionListener(
ActionListener{
public override function actionPerformed(e:ActionEvent){
action();
}
}
);

return button;
}

}

Stage {
title: "Application title"
width: 250
height: 80
scene: Scene {
content: MyButtonComponent {
text: "Click Me!"
toolTipText: "Tool tip text"
action: function(){
println("Hello World!");
}
}
}
}
[/code]

gillman
Offline
Joined: 2006-06-18

Thanks! That works great.