温馨提示×

java fxml与swing如何结合

小樊
81
2024-09-15 15:50:30
栏目: 编程语言

Java FXML 和 Swing 是两种不同的 Java GUI 框架,它们之间的结合可以通过将它们嵌入到彼此的容器中来实现。这里是一个简单的示例,展示了如何在 FXML 应用程序中嵌入 Swing 组件,以及如何在 Swing 应用程序中嵌入 FXML 组件。

  1. 在 FXML 应用程序中嵌入 Swing 组件:

首先,创建一个简单的 Swing 组件,例如一个 JLabel:

import javax.swing.*;

public class SwingComponent {
    public static JComponent createSwingComponent() {
        return new JLabel("Hello from Swing!");
    }
}

然后,在 FXML 控制器中,使用 SwingNode 将 Swing 组件嵌入到 FXML 界面中:

import javafx.embed.swing.SwingNode;
import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;

public class FXMLController {
    @FXML
    private AnchorPane anchorPane;

    @FXML
    private void initialize() {
        SwingNode swingNode = new SwingNode();
        swingNode.setContent(SwingComponent.createSwingComponent());
        anchorPane.getChildren().add(swingNode);
    }
}
  1. 在 Swing 应用程序中嵌入 FXML 组件:

首先,创建一个简单的 FXML 文件(例如 FXMLComponent.fxml):

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?><AnchorPane xmlns:fx="http://javafx.com/fxml">
   <Label text="Hello from FXML!" />
</AnchorPane>

然后,在 Swing 应用程序中,使用 JFXPanel 将 FXML 组件嵌入到 Swing 界面中:

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javax.swing.*;

public class SwingApp {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Swing App");
        final JFXPanel fxPanel = new JFXPanel();
        frame.add(fxPanel);
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        Platform.runLater(() -> {
            try {
                Parent root = FXMLLoader.load(SwingApp.class.getResource("FXMLComponent.fxml"));
                Scene scene = new Scene(root);
                fxPanel.setScene(scene);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}

这样,你就可以在 FXML 应用程序中嵌入 Swing 组件,以及在 Swing 应用程序中嵌入 FXML 组件了。请注意,这两种方法都需要在 JavaFX 应用程序线程上运行,因此需要使用 Platform.runLater()

0