JAVA 如何在 swing 中将 JAVAFX 的标签嵌入 JPanel?

3

我如何将使用JavaFX创建的自定义标签嵌入到现有Swing的JPanel中?

例如:

自定义JavaFX标签:

public class CustomJavaFXLabel extends Label{
    public CustomJavaFXLabel(){
        super();    
        setFont("blah blah blah");
        setText("blah blah blah");
          /*
           *and so on...
           */
    }
}

在 Swing 中存在的 JPanel

public class SwingApp(){
    private JPanel jpanel;

    public SwingApp(){
        jpanel = new JPanel();
        jpanel.add(new CustomJavaFXLabel()); //this line does not work
    }
}

我得到的错误是:

The method add(Component) in the type Container is not applicable for argument (CustomJavaFXLabel)

我知道为了这个目的,最好使用JLabel来创建自定义标签。但是,由于某些限制,我需要使用FX来创建自定义标签。

谢谢。

1个回答

5
JavaFX: Interoperability, §3 Integrating JavaFX into Swing Applications所示,将您的自定义javafx.scene.control.Label添加到javafx.embed.swing.JFXPanel中。因为JFXPanel是一个java.awt.Container,所以可以将其添加到您的Swing布局中。以下是一些示例:here

label image

import java.awt.Dimension;
import java.awt.EventQueue;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javax.swing.JFrame;
/**
 * @see https://dev59.com/DZ3ha4cB1Zd3GeqPTWDG
 */
public class LabelTest {

    private void display() {
        JFrame f = new JFrame("LabelTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JFXPanel jfxPanel = new JFXPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(320, 240);
            }
        };
        initJFXPanel(jfxPanel);
        f.add(jfxPanel);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private void initJFXPanel(JFXPanel jfxPanel) {
        Platform.runLater(() -> {
            Label label = new Label(
                System.getProperty("os.name") + " v"
                + System.getProperty("os.version") + "; Java v"
                + System.getProperty("java.version"));
            label.setBackground(new Background(new BackgroundFill(
                Color.ALICEBLUE, CornerRadii.EMPTY, Insets.EMPTY)));
            StackPane root = new StackPane();
            root.getChildren().add(label);
            Scene scene = new Scene(root);
            jfxPanel.setScene(scene);
        });
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new LabelTest()::display);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接