JavaFX-嵌入Swing页面中方法

0.前言

最近刚入手java开发客户端程序,在选择Swing与JavaFX两个GUI框架时,发现Swing已经停止维护,并且发现JavaFX框架能够嵌入Swing,说明JavaFX基本使用Swing应该是没有问题的,于是就选择了JavaFX作为开发客户端程序的GUI框架。

1.前期准备

前期用了JavaFx搭建了简单的架子,能够实现点击菜单,切换到各自页面


JavaFX简单界面.jpg

2.如何嵌入Swing页面

查阅了JavaFX的官方文档,发现了SwingNode这个类,改类就是专门实现Swing转换成JavaFx的关键类,并且该文档给出了个例子

This class is used to embed a Swing content into a JavaFX application. The content to be displayed is specified with the setContent(javax.swing.JComponent) method that accepts an instance of Swing JComponent. The hierarchy of components contained in the JComponent instance should not contain any heavyweight components, otherwise SwingNode may fail to paint it. The content gets repainted automatically. All the input and focus events are forwarded to the JComponent instance transparently to the developer.

Here is a typical pattern which demonstrates how SwingNode can be used:

public class SwingFx extends Application {
     @Override
     public void start(Stage stage) {
         final SwingNode swingNode = new SwingNode();
         createAndSetSwingContent(swingNode);

         StackPane pane = new StackPane();
         pane.getChildren().add(swingNode);

         stage.setScene(new Scene(pane, 100, 50));
         stage.show();
     }

     private void createAndSetSwingContent(final SwingNode swingNode) {
         SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                 swingNode.setContent(new JButton("Click me!"));
             }
         });
     }

     public static void main(String[] args) {
         launch(args);
     }
 }

关键方法在 swingNode.setContent(JComponent content),只能嵌入JComponent 类别的组件,像JFrame、JDialog等不适JComponent类别的都不能够嵌入


JComponent继承结构.jpg

3.实现JavaFx嵌入Swing页面

我在某个菜单的点击事件中进行嵌入操作,代码如下

                System.out.println("点击事件");
                JButton jButton1 = new JButton("btn1");
                JButton jButton2 = new JButton("btn2");
                JButton jButton3 = new JButton("btn3");
                JButton jButton4 = new JButton("btn4");
                JButton jButton5= new JButton("btn5");
                JPanel jPanel = new JPanel();
                jPanel.setLayout(new BorderLayout());
                jPanel.add(jButton1,BorderLayout.NORTH);
                jPanel.add(jButton2,BorderLayout.CENTER);
                jPanel.add(jButton3,BorderLayout.SOUTH);
                jPanel.add(jButton4,BorderLayout.EAST);
                jPanel.add(jButton5,BorderLayout.WEST);
                final SwingNode swingNode = new SwingNode();
                swingNode.setContent(jPanel);
                borderPane.setCenter(swingNode);

4.点击显示嵌入Swing页面

JavaFX嵌入Swing页面.jpg

你可能感兴趣的:(JavaFX-嵌入Swing页面中方法)