简体   繁体   中英

JFrame-JDialog comunication

I have a JFrame main window wich has a Register button on in.Click the register button and the JDialog windows pops out.

public void mouseClicked(MouseEvent e) {
                Reg new1=new Reg(users);
                new1.setVisible(true);
            }

The JDialog window has 2 buttons->Register,Cancel.Both of them must do something and close the Dialog window.

This is what I tried. In the Reg(Dialog window)---> btnCancel:

public void mouseClicked(MouseEvent e) {
                        dialog.dispose();
                        System.out.println("Reg disposed by cancel button");
                    }

This closes the D window when run just the D window but I guess when executed from the main window(Button clicked) it still exists like an object in the main fraim"class" and doesn't close.What should I do ?How do I make it close ?

You need some way for the frame to determine how the dialog was closed

// Why are you using a `MouseListener` on buttons??
// User use keyboards to, use an ActionListener instead
public void mouseClicked(MouseEvent e) {
    Reg new1=new Reg(users);
    new1.setVisible(true);
    switch (new1.getDisposeState()) {
        case Reg.OK:
            // Clicked Ok
            break;
        case Reg.CANCEL:
            // Clicked cancel or was closed by press [x]
            break;
    }
}

Then in your Reg class, you need to maintain information about the state...

public class Reg extends JDialog {
    public static final int OK = 0;
    public static final int CANCEL = 1;

    private int disposeState = CANCEL;

    //...

    public int getDisposeState() {
        return disposeState
    }

    public void setDisposeState(int state) {
        disposeState = state;
    }

Then you change the state

// Why are you using a `MouseListener` on buttons??
// User use keyboards to, use an ActionListener instead
public void mouseClicked(MouseEvent e) {
    setDisposeState(CANCEL);
    dialog.dispose();
    System.out.println("Reg disposed by cancel button");
}

This all assumes that your dialog is modal of course...

Now, having said all that, personally, I would make your Reg class a JPanel and add it to a JOptionPane instead or use a CardLayout

Take a look at:

...for more details

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