Взаимодействие между Swing и Javafx: закрытие родительского этапа Javafx из встроенного приложения Swing - PullRequest
1 голос
/ 28 мая 2020

Я встроил приложение Swing в приложение JavaFx с помощью SwingNode, как показано ниже:

final SwingNode swingNode = new SwingNode();
SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
            swingNode.setContent(new ButtonHtml());        
            }          
        });

Кнопка Html - это приложение Swing, как показано ниже:

public class ButtonHtml extends JPanel
                            implements ActionListener {
    protected JButton b1, b3;

    public ButtonHtml() {
        ImageIcon buttonIcon = createImageIcon("images/down.gif");      

        b1 = new JButton("<html><center><b><u>D</u>isable</b><br>"
                         + "<font color=#ffffdd>FX button</font>", 
                         buttonIcon);
        Font font = b1.getFont().deriveFont(Font.PLAIN);
        b1.setFont(font);
        b1.setVerticalTextPosition(AbstractButton.CENTER);
        b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
        b1.setMnemonic(KeyEvent.VK_D);
        b1.setActionCommand("disable");


        b3 = new JButton("<html><center><b><u>E</u>nable</b><br>"
                         + "<font color=#ffffdd>FX button</font>", 
                         buttonIcon);
        b3.setFont(font);
        //Use the default text position of CENTER, TRAILING (RIGHT).
        b3.setMnemonic(KeyEvent.VK_E);
        b3.setActionCommand("enable");
        b3.setEnabled(false);

        //Listen for actions on buttons 1 and 3.
        b1.addActionListener(this);
        b3.addActionListener(this);

        b1.setToolTipText("Click this button to disable the FX button.");
        b3.setToolTipText("Click this button to enable the FX button.");

        //Add Components to this container, using the default FlowLayout.
        add(b1);
        add(b3);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("disable".equals(e.getActionCommand())) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    //close the parent javafx window

                }
            });


            b1.setEnabled(false);
            b3.setEnabled(true);
        } else {
            Platform.runLater(new Runnable() {
               @Override
               public void run() {
                   //do something
               }
            });
            b1.setEnabled(true);
            b3.setEnabled(false);
        }
    }

    /** Returns an ImageIcon, or null if the path was invalid.
     * @param path
     * @return  */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = ButtonHtml.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

}

Теперь в моем приложении javafx я встроил SwingNode в панель, создал сцену и выполнил stage.show, чтобы открыть окно javafx:

BorderPane pane = new BorderPane();

        Image fxButtonIcon = new Image(getClass().getResourceAsStream("images/middle.gif"));

        fxbutton = new Button("FX button", new ImageView(fxButtonIcon));
        fxbutton.setTooltip(new Tooltip("This middle button does nothing when you click it."));
        fxbutton.setStyle("-fx-font: 22 arial; -fx-base: #cce6ff;");
        pane.setTop(swingNode);
        pane.setCenter(fxbutton);


        Scene scene = new Scene(pane, 300, 100);
        stage.setScene(scene);
        stage.setTitle("Enable FX Button");
        stage.show();

Мне нужно знать, как мы можем вызвать скрытие / удалить / закрыть родительское окно Javafx из встроенного приложения Swing. В основном я хочу нажать кнопку (в приведенном выше примере, скажем, кнопку b1) и закрыть окно javafx. Обратите внимание, что приложение Swing и приложение javafx независимы.

1 Ответ

1 голос
/ 28 мая 2020

Достаточно чистый подход - просто определить поле в вашем классе ButtonHtml, представляющее, что делать при нажатии b1.

Включив это и модернизируя реализации прослушивателя действий, вы можете:

public class ButtonHtml extends JPanel {

    protected JButton b1, b3;

    private Runnable onCloseRequested = () -> {} ;

    public void setOnCloseRequested(Runnable onCloseRequested) {
        this.onCloseRequested = onCloseRequested ;
    }

    public Runnable getOnCloseRequested() {
        return onCloseRequested ;
    }

    public ButtonHtml() {
        ImageIcon buttonIcon = createImageIcon("images/down.gif");      

        b1 = new JButton("<html><center><b><u>D</u>isable</b><br>"
                         + "<font color=#ffffdd>FX button</font>", 
                         buttonIcon);
        Font font = b1.getFont().deriveFont(Font.PLAIN);
        b1.setFont(font);
        b1.setVerticalTextPosition(AbstractButton.CENTER);
        b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
        b1.setMnemonic(KeyEvent.VK_D);
        b1.setActionCommand("disable");


        b3 = new JButton("<html><center><b><u>E</u>nable</b><br>"
                         + "<font color=#ffffdd>FX button</font>", 
                         buttonIcon);
        b3.setFont(font);
        //Use the default text position of CENTER, TRAILING (RIGHT).
        b3.setMnemonic(KeyEvent.VK_E);
        b3.setActionCommand("enable");
        b3.setEnabled(false);

        //Listen for actions on buttons 1 and 3.
        b1.addActionListener(e -> {
            Platform.runLater(onCloseRequested);
            b1.setEnabled(false);
            b3.setEnabled(true);
        });
        b3.addActionListener(e -> { /* ... */ });

        b1.setToolTipText("Click this button to disable the FX button.");
        b3.setToolTipText("Click this button to enable the FX button.");

        //Add Components to this container, using the default FlowLayout.
        add(b1);
        add(b3);
    }



    /** Returns an ImageIcon, or null if the path was invalid.
     * @param path
     * @return  */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = ButtonHtml.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

}

А дальше можно просто

final SwingNode swingNode = new SwingNode();
SwingUtilities.invokeLater(() -> {
    ButtonHtml buttonHtml = new ButtonHtml();
    buttonHtml.setOnCloseRequested(() -> swingNode.getScene().getWindow().hide());
    swingNode.setContent(buttonHtml);        
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...