在Swing JFrame上隐藏并显示JFXPanel



我想在swing 中的javaFx应用程序中隐藏和显示FXPanel控件

我想点击一个按钮,FXPanel控件应该被隐藏,点击另一个控件应该再次可见,它被隐藏而不再可见。

使用以下代码。

public class abc extends JFrame
{
JFXPanel fxpanel;
Container cp;
public abc()
{
cp=this.getContentPane();
cp.setLayout(null);
JButton b1= new JButton("Ok");
JButton b2= new JButton("hide");
cp.add(b1);
cp.add(b2);
b1.setBounds(20,50,50,50);
b2.setBounds(70,50,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
fxpanel= new JFXPanel();
cp.add(fxpanel);
fxpanel.setBounds(600,200,400,500);
}
public void actionPerformed(ActionEvent ae)
{ 
if(ae.getActionCommand().equals("OK"))
{
fxpanel.setVisible(true);
}
if(ae.getActionCommand().equals("hide"))
{
fxpanel.hide();
}
Platform.runLater(new Runnable())
{
public void run()
{
init Fx(fxpanel);
}}
);
}
private static void initFX(final JFXPanel fxpanel) 
{
Group group = ne Group();
Scene scene= new Scene(group);
fxpanel.setScene(scene);
WebView webview= new WebView();
group.getChildren().add(webview);
webview.setMinSize(500,500);
webview.setMaxSize(500,500);
eng=webview.getEngine();
File file= new File("d:/new folder/abc.html");
try
{
eng.load(file.toURI().toURL().toString());
}
catch(Exception ex)
{
}
}
public static void main(String args[])
{
abc f1= new abc();
f1.show();
}
}

除了一些拼写错误外,您的代码还有多个问题:

1) 如果您使用ActionEvent#getActionCommand来确定单击了哪个按钮,则必须首先在按钮上设置操作命令属性。操作命令与按钮的文本不同。

2) 您添加的两个按钮具有相同的坐标,因此其中一个不会显示。

3) 不要使用不推荐使用的hide()-方法来隐藏JFXPanel,使用setVisisble(false)

此外,一些通用的指针:

4) 不要对普通UI使用null布局。曾经

5) 阅读java命名约定。这不仅仅是我的挑剔,它将帮助你更好地理解别人的代码,并帮助其他人维护你的代码。

6) 通过SwingUtilities#invokeLater从EDT调用显示摆动组件的代码,就像使用Platform类一样。像您所做的那样从主线程调用swing在大多数情况下都会起作用,但偶尔会出现难以跟踪的错误。

最新更新