有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java大小带有嵌入式SwingNode的JavaFX对话框

我正在创建一个自定义JavaFX对话框,我想重用一个扩展JPanel的旧类。我将面板嵌入了一个SwingNode中,并将其设置为对话框内容窗格。可以添加,但对话框的大小不能显示整个面板。我的理解是JPanel在被添加到UI之前不会进行所有的大小调整,所以当它被添加到SwingNode中,然后SwingNode被添加到对话框中时,它的大小仍然是0,0。对话框实际显示后,面板的大小会更新一段时间,但对话框的大小不会调整

以下是我的最小可复制示例:

//Various imports here

public class SwingDialogInFxTest extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Pane root = new Pane();
        
        Button showDialogButton = new Button("Show FX/Swing dialog");
        showDialogButton.setOnAction(e -> new DialogWithSwingPanel().show());
        
        root.getChildren().add(showDialogButton);
        
        primaryStage.setScene(new Scene(root, 200, 200));
        primaryStage.show();
    }

    public static void main(String args[]) {
        launch(args);
    }
    
    private class DialogWithSwingPanel extends Dialog<Void> {
        public DialogWithSwingPanel() {
            SwingNode swingNode = new SwingNode();
            SwingUtilities.invokeLater(() -> {
                JPanel swingPanel = new SomeSwingPanel();
                swingNode.setContent(swingPanel);
            });
            
            getDialogPane().setContent(swingNode);
        }
    }
    
    private class SomeSwingPanel extends JPanel {
        
        public SomeSwingPanel() {
            //Make this big just to illustrate my point
            this.setMinimumSize(new Dimension(1000,1000));
        }
    }
}

结果是对话框看起来很小,尽管面板应该是1000乘1000

Tiny dialog

我确实想出了一个几乎能奏效的方法,但我还是不太满意。我在面板中添加了一个ComponentListener,然后用它来调整对话框的大小。换句话说,我将DialogWithSwingPanel构造函数更改为:

    private class DialogWithSwingPanel extends Dialog<Void> {
        public DialogWithSwingPanel() {
            
            SwingNode swingNode = new SwingNode();
            SwingUtilities.invokeLater(() -> {
                JPanel swingPanel = new SomeSwingPanel();
                swingNode.setContent(swingPanel);
                
                swingPanel.addComponentListener(new ComponentAdapter() {
                    @Override
                    public void componentResized(ComponentEvent e) {
                        DialogWithSwingPanel.this.setWidth(swingPanel.getWidth());
                        DialogWithSwingPanel.this.setHeight(swingPanel.getHeight());
                    }
                });
            });
            
            getDialogPane().setContent(swingNode);
            
        }
    }

在我的示例中,通过运行上面的代码,它看起来确实可以工作,但是当你在一个实际包含内容的面板上尝试时,你会注意到其中一些内容被切断了。这是因为我将对话框大小设置为与面板大小相匹配,但实际上它应该更大一些,以考虑一些边距和标题栏(我认为)。但是,设置SwingNode大小或设置从getDialogPane()返回的值的大小没有任何作用,所以目前我能做的最好的解决方案是上面的解决方案,只需在宽度上加10,在高度上加20。这并不理想


共 (0) 个答案