简体   繁体   中英

Java - How to close a window on open of a dialog

i created a dialog class that opens when a JLabel is clicked but i want the main window to close when the label is clicked and a more bigger issue is that the label is in a class that extends a JPanel now if the label is clicked the panel goes as in setVisible(false), do you get what i mean, but when i tried to use polymorphism in the panel class to obtain both the main window class and the dialog it proved successful but when the label is clicked an new similar main wnidow pops up and immediately disappears. ie it duplicates the main window, i know that this problem might look like a chalenge because there are no codes, the file is too complicated but i kmow there is a pro out there who can get a picture of what this code is and help me, thank you

"an new similar main wnidow pops up and immediately disappears. ie it duplicates the main window, " -

Seeing how your JPanel is a separate class, it seems to me like you have a referencing issue. I bet what you did was create a new MainWindow so that you could reference it. Like

mousePressed(MouseEvent e) {
    MainWindow window = new MainWindow();
    window.dispose();
} 

That would definitely explain the the issue. There are a few ways to deal with this. I'm going to give you the rookie way, since you still seem like a rook :D You'll probably learn more proper ways as your learning gets deeper. So you can do something like below, where you pass the reference of the MainWindow to the JPanel class, instead of creating a new MainWindow

public class MyPanel extends JPanel {
    private MainWindow window;

    public MyPanel(final MainWindow window) {
        this.window = window;
        JLabel label = new Label();
        label.addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e) {
                window.setVisible(false); // or dispose
            }
        });
    } 
}

When you instantiate the MyPanel , pass the reference of the MainWindow to the MyPanel , like MyPanel panel = new MyPanel(MainWindow.this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM