【Java】SwingとJavaFXの相互連携
本稿ではJavaのSwingアプリケーションでJavaFXと連携して機能を埋め込む方法とJavaFXアプリケーションでSwingと連携して機能を埋め込む方法を見ていきます。
Swingアプリケーション内で一部JavaFXの機能を利用したい場合や、JavaFX内に既にSwingで作成したプログラムをそのまま使いたい場合に利用できます。
Swingアプリケーション内にJavaFX機能の埋め込み
JavaFXのJFXPanelクラスを利用することで実現できます。
このクラスはJComponentを継承しているため、他のJPanelと同じように使用できます。
追加でJavaFXのSceneを埋め込むメソッドが用意されているのでそれを利用します。
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(Test::run);
}
public static void run() {
JFrame f = new JFrame("テスト");
//Swingで上側にパネルの挿入
JPanel topPane = new JPanel();
topPane.setBackground(Color.LIGHT_GRAY);
f.add(topPane,BorderLayout.NORTH);
//JavaFXで真ん中にシーンを挿入
JFXPanel centerPane = new JFXPanel();
StackPane stPane = new StackPane();
Text text = new Text();
text.setText("Swing内にJavaFX機能の埋め込みテスト");
stPane.getChildren().add(text);
Scene scene = new Scene(stPane);
centerPane.setScene(scene);
f.add(centerPane);
//Swingで下側にパネルの挿入
JPanel bottomPane = new JPanel();
bottomPane.setBackground(Color.GRAY);
f.add(bottomPane,BorderLayout.SOUTH);
f.setSize(400, 300);
f.setVisible(true);
}
}

JavaFXアプリケーション内にSwing機能の埋め込み
SwingNodeというクラスで実現できます。
このクラスはNodeクラスを継承しており、Nodeと同じように利用することができます。
追加でJComponentオブジェクトを埋め込むメソッドが用意されているので、それを利用します。
import javax.swing.JLabel;
import javafx.application.Application;
import javafx.embed.swing.SwingNode;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class Test extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
//ルートパネル
BorderPane bPane = new BorderPane();
//JavaFXで上側にパネル追加
HBox top = new HBox();
top.setMinHeight(20);
top.setBackground(
new Background(
new BackgroundFill(Color.LIGHTGRAY,CornerRadii.EMPTY,Insets.EMPTY)
)
);
bPane.setTop(top);
//Swingで真ん中にラベル追加
SwingNode swing = new SwingNode();
JLabel label = new JLabel("JavaFX内にSwing機能の埋め込みテスト");
swing.setContent(label);
bPane.setCenter(swing);
//JavaFXで下側にパネル追加
HBox bottom = new HBox(10);
bottom.setMinHeight(20);
bottom.setBackground(
new Background(
new BackgroundFill(Color.GRAY,CornerRadii.EMPTY,Insets.EMPTY)
)
);
bPane.setBottom(bottom);
Scene scene = new Scene(bPane, 400, 300);
primaryStage.setTitle("テスト");
primaryStage.setScene(scene);
primaryStage.show();
}
}








ディスカッション
コメント一覧
まだ、コメントがありません