我知道如何使用JFXPanel在swing中集成javafx组件。但是很难对组件的所有属性进行编码。此外,也不可能将css属性赋予javafx组件。那么,在JFXPanel中集成整个fxml文件是可能的吗?谢谢
发布于 2014-04-25 12:07:00
要将css属性赋予javafx组件,只需在JFXPanel上设置的场景中添加一个样式表即可。
要使用FXML定义显示在JFXPanel中的组件,可以像往常一样使用FXMLLoader加载FXML文件,并将结果用作JFXPanel的Scene的根。
例如:
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() );
}
}FXComponents.fxml:
<?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>style.css:
@CHARSET "UTF-8";
.button {
-fx-base: cornflowerblue ;
}
.text-field {
-fx-text-fill: blue ;
-fx-font-size: 18pt ;
}Controller.java:
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
public class Controller {
@FXML
private TextField textField ;
@FXML
private void printMessage() {
System.out.println(textField.getText());
}
}https://stackoverflow.com/questions/23291993
复制相似问题