Java FXML 和 Swing 是兩種不同的 Java GUI 框架,它們之間的結合可以通過將它們嵌入到彼此的容器中來實現。這里是一個簡單的示例,展示了如何在 FXML 應用程序中嵌入 Swing 組件,以及如何在 Swing 應用程序中嵌入 FXML 組件。
首先,創(chuàng)建一個簡單的 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);
}
}
首先,創(chuàng)建一個簡單的 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()
。