0

我在 JavaFx 中编写了一个简单的应用程序并想在其中使用 swingNode,所以我在更改节点的大小或位置时遇到了问题

public class SwingFx extends Application {

    @Override
    public void start (Stage stage) {
        final SwingNode swingNode = new SwingNode();

        createSwingContent(swingNode);

        StackPane pane = new StackPane();
        pane.getChildren().add(swingNode);

        stage.setTitle("Swing in JavaFX");
        stage.setScene(new Scene(pane, 250, 150));
        stage.show();
    }

    private void createSwingContent(final SwingNode swingNode) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JButton jButton = new JButton("Click me!");
                jButton.setBounds(0,0,5,5);
                swingNode.setContent(jButton);

            }
        });
    }
}

我设置了 JButton 的边界,但它不起作用,当我运行应用程序时,按钮出现在中心并且它的默认宽度和高度

4

1 回答 1

2

setbounds()如果您想要工作,您应该使用父容器并将其布局设置为 null

public class SwingFx extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start (Stage stage) {
        final SwingNode swingNode = new SwingNode();

        createSwingContent(swingNode);

        StackPane pane = new StackPane();
        pane.getChildren().add(swingNode);

        stage.setTitle("Swing in JavaFX");
        stage.setScene(new Scene(pane, 250, 150));
        stage.show();
    }

    private void createSwingContent(final SwingNode swingNode) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JButton jButton = new JButton("Click me!");
                jButton.setBounds(10,10,50,50);

                JPanel panel = new JPanel();
                panel.setLayout(null);
                panel.add(jButton);

                swingNode.setContent(panel);

            }
        });
    }
}
于 2016-07-31T15:53:12.420 回答