Java的jpanel里的标签,JAVA如何将JAVAFX的标签嵌入到JPanel中?

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.

解决方案

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.

hLb4s.png

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值