gpt4 book ai didi

java - 在 swing 中使用 JFXPanel 集成 fxml 文件

转载 作者:行者123 更新时间:2023-11-30 08:23:55 37 4
gpt4 key购买 nike

我知道如何使用 JFXPanel 在 swing 中集成 javafx 组件。但是很难为组件的所有属性编写代码。此外,也不可能将 css 属性赋予 javafx 组件。那么是否可以将整个 fxml 文件集成到 JFXPanel 中?谢谢

最佳答案

要为 javafx 组件提供 css 属性,只需将样式表添加到您在 JFXPanel 上设置的场景即可。

要使用 FXML 定义显示在 JFXPanel 中的组件,请照常使用 FXMLLoader 加载 FXML 文件,并将结果用作 的根JFXPanel 的>场景

例如:

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>

样式.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());
}
}

关于java - 在 swing 中使用 JFXPanel 集成 fxml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291993/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com