Diogo Santos
Diogo Santos

Reputation: 830

Close windows without closing Application

Good afternoon!

I have this code:

private static class ClickListener implements ActionListener {

    public ClickListener() {

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JFrame frame = new JFrame();
        JLabel label = new JLabel("Opção Indisponivel");
        JPanel panel = new JPanel();
        frame.add(label, BorderLayout.CENTER);
        frame.setSize(300, 400);
        JButton button = new JButton("Voltar");
        button.addActionListener(new CloseWindowListener());
        panel.add(button);
        frame.add(panel, BorderLayout.SOUTH);
        frame.setVisible(true);
    }
}

private static class CloseWindowListener implements ActionListener {

    public CloseWindowListener() {
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        setVisible(false);
    }
}

What I want to do is when i click on the button "voltar" (which is in another window, not on the "main" one as you can see) it closes the windows but not the app itselft. The setVisible line gives me an error about that it cannot be referenced by a static context which I understand because I need the reference of the frame. How do I solve this?

EDIT: Changed JFrame to JDialog but still no sucess. Both windows are shutdown.

Thanks in advance, Diogo Santos

Upvotes: 0

Views: 340

Answers (1)

camickr
camickr

Reputation: 324118

The setVisible line gives me an error about that it cannot be referenced by a static context which I understand because I need the reference of the frame. How do I solve this?

You can access the component that generated the event. Then you can find the window the component belongs to. This will give you generic code to hide any window:

//setVisible(false);
JButton button = (JButton)e.getSource();
Window window = SwingUtilities.windowForComponent(button);
window.setVisible(false);

You can also check out Closing an Application. The ExitAction can be added to your button. Now when you click the button it will be like clicking the "x" (close) button of the window. That is whatever default close operation your specify for the window will be invoked.

Upvotes: 1

Related Questions