JAVA How to embed JAVAFX's label into a JPanel

2019-04-14 15:14发布

问题:

How can I embed a custom label I created using JAVAFX into an existing swing's JPanel?

E.g.

Custom JavaFX Label:

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

Existing JPanel in swing

public class SwingApp(){
    private JPanel jpanel;

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

Error I got is:

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

I understand that to for this, I am better off using JLabel to create the custom label. However, due to certain constraints I was required to use FX for the custom Label.

Thanks.

回答1:

As shown in JavaFX: Interoperability, §3 Integrating JavaFX into Swing Applications, add your custom javafx.scene.control.Label to a javafx.embed.swing.JFXPanel. Because a JFXPanel is a java.awt.Container, it can be added to your Swing layout. Several examples may be found here and below.

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://stackoverflow.com/q/41159015/230513
 */
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);
    }
}