我知道如何使用JFXPanel将javafx组件集成到swing中。但它很难编写组件的所有属性。此外,也不可能为javafx组件提供css属性。那么可以将整个fxml文件集成到JFXPanel中吗? 谢谢
答案 0 :(得分:3)
要为javafx组件提供css属性,只需将样式表添加到您在JFXPanel
上设置的场景。
要使用FXML定义JFXPanel
中显示的组件,请照常使用FXMLLoader
加载FXML文件,并将结果作为Scene
的根用于{ {1}}。
例如:
JFXPanel
FXComponents.fxml:
import java.awt.BorderLayout;
import java.io.IOException;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
private void initSwingComponents() {
JFrame frame = new JFrame("Java FX in Swing");
frame.setLayout(new BorderLayout());
final JFXPanel jfxPanel = new JFXPanel();
frame.add(jfxPanel, BorderLayout.CENTER);
final JPanel swingButtons = new JPanel();
final JButton okButton = new JButton("OK");
okButton.addActionListener(event -> System.out.println("Swing says 'OK'"));
final JButton exitButton = new JButton("Exit");
exitButton.addActionListener(event -> System.exit(0));
swingButtons.add(okButton);
swingButtons.add(exitButton);
frame.add(swingButtons, BorderLayout.SOUTH);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
okButton.requestFocus();
Platform.runLater(() -> initFX(jfxPanel));
}
private void initFX(JFXPanel jfxPanel) {
try {
Parent root = FXMLLoader.load(getClass().getResource("FXComponents.fxml"));
Scene scene = new Scene(root, 250, 150);
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
jfxPanel.setScene(scene);
} catch (IOException exc) {
exc.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
Test test = new Test();
SwingUtilities.invokeLater(() -> test.initSwingComponents() );
}
}
的style.css:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.control.Button?>
<VBox xmlns:fx="http://javafx.com/fxml" fx:controller="Controller" spacing="5" alignment="CENTER">
<TextField fx:id="textField" promptText="Enter message here"/>
<Button text="Print message" onAction="#printMessage" />
</VBox>
Controller.java:
@CHARSET "UTF-8";
.button {
-fx-base: cornflowerblue ;
}
.text-field {
-fx-text-fill: blue ;
-fx-font-size: 18pt ;
}