[英]JAVA How to embed JAVAFX's label into a JPanel in swing?
How can I embed a custom label I created using JAVAFX into an existing swing's JPanel? 如何将使用JAVAFX创建的自定义标签嵌入到现有的swing的JPanel中?
Eg 例如
Custom JavaFX Label: 自定义JavaFX标签:
public class CustomJavaFXLabel extends Label{
public CustomJavaFXLabel(){
super();
setFont("blah blah blah");
setText("blah blah blah");
/*
*and so on...
*/
}
}
Existing JPanel in swing 现有的JPanel摇摆不定
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. 我知道,为此,我最好使用JLabel创建自定义标签。 However, due to certain constraints I was required to use FX for the custom Label. 但是,由于某些限制,我需要对自定义标签使用FX。
Thanks. 谢谢。
As shown in JavaFX: Interoperability, §3 Integrating JavaFX into Swing Applications , add your custom javafx.scene.control.Label
to a javafx.embed.swing.JFXPanel
. 如JavaFX:互操作性§3中所示,将JavaFX集成到Swing应用程序中 ,将自定义javafx.scene.control.Label
添加到javafx.embed.swing.JFXPanel
。 Because a JFXPanel
is a java.awt.Container
, it can be added to your Swing layout. 由于JFXPanel
是 java.awt.Container
,因此可以将其添加到Swing布局中。 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.