在Swing中隐藏和显示JavaFX图表

时间:2013-05-26 17:01:39

标签: swing charts javafx show-hide

您想与我分享我的Warkaround,这个问题需要花费数小时才能解决,因为我找不到任何直接的答案。

我正在实现一个Swing应用程序,它根据其状态显示JavaFX Chart(实时折线图)或其他一些内容(在我的例子中它是一个JFreeChart)。 我添加并删除了面板到我的UI,但是对于大多数内容都可以正常工作。

使用JavaFX时,我的内容一旦显示然后隐藏就不会显示。

请参阅下面的非工作示例代码:

CustomFXPanel pn1 = new CustomFXPanel(); //JPanel containing JavaFX Chart
CustomPanel pn2 = new CustomPanel();     //Extends JPanel
JPanel pnContent; //PlaceHolder for either Panel



/**
 * Constructor
 */
public MyJFrame(){
    init(); //Set up JFrame Size, title etc.
    setLayout(new GridLayout(1,1)); //Show the Content all across the Frame
    pnContent = pn1;
    add(pnContent);
}    

/**
 * Changes Mode of Application
 * @param showFX: True = show fxChart, False = show other Panel
 */
public void changePanel(boolean showFX){
    if(showFX){  //Show FX Chart
        if(!pnContent.equals(pn1)){
            remove(pnContent);
            pnContent = pn1;
            add(pnContent);
        }
    }else{  //Show other Panel
        if(!pnContent.equals(pn2)){
            remove(pnContent);
            pnContent = pn2;
            add(pnContent);
        }
    }
}

问题: 它会在启动时显示正常。但是,当更改为pn2然后再返回到pn1时,pn1中的JFXPanel将无法显示。

我通过在pn1中重新调用myFXPanel.setStage(new Stage(myJFXChart))来实现它。然而,这总是抛出IllegalArgumentsException,......“已经设置为另一个场景的根”。 - 它有效,但我认为让异常飞来飞去是一种丑陋而不好的做法。

令人讨厌的是,任何处理此异常的企图都导致专家组不再出现。 这包括:

JFXPanel myFXPanel = new JFXPanel();
LineChart<Number, Number> chart;
....
//Inside reload method
//With parts inside then outside Platform.runLater(new Runnable()) {...}
myFXPanel.invalidate();
myFXPanel.removeAll();
try{
    setStage(newStage(chart));
}catch(Exception ex){}

1 个答案:

答案 0 :(得分:1)

我能找到的唯一解决方法是滥用JSplitPane(setDivider(0)并将任一方设置为setVisible(false)):示例代码如下。

CustomFXPanel pn1 = new CustomFXPanel(); //JPanel containing JavaFX Chart
CustomPanel pn2 = new CustomPanel();     //Extends JPanel
JSplitPane spContent;
…
/**
 * Constructor
 */
public MyJFrame(){
    init(); //Set up JFrame Size, title etc.
    spContent.setDividerSize(0);        //Hide the Divider
    spContent.setLeftComponent(pn1);    
    spContent.setLeftComponent(pn2);
    pn1.setVisible(true);               //By default show pn1
    pn2.setVisible(false);              //Hide this Panel. JSplitPane will adjust itself (either left or right will take up all space).

    setLayout(new GridLayout(1,1)); //Show the Content all across the Frame
    add(spContent);
}    

/**
 * Changes Mode of Application
 * @param showFX: True = show fxChart, False = show other Panel
 */
public void changePanel(boolean showFX){
    if(showFX){  //Show FX Panel
        pn1.setVisible(true);    //spContent will adjust itself
        pn2.setVisible(false);
    }else{  //Show normal Panel
        pn1.setVisible(false);
        pn2.setVisible(true);
    }
}

如果您有任何人找到更优雅的解决方案,请随时写下您的答案。 我已经在这里写了我自己的解决方法,我认为,我不是唯一有这个问题的人。

我希望我能提供帮助。 干杯