Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

swing - Button on FrameOne shall close FrameTwo. ActionListener referes object of another class in JAVA

I have two frames in separate classes (FrameOne and FrameTwo) FrameOne has two buttons. One to open FrameTwo and One shall close FrameTwo. How to open FrameTwo I know. But not how to close from Frame One. How do I code it to make it working? Thanks. (I know that there are similar questions. I red them all. But it didn't gave me the answer. Also GUI guides didn't helped.)

public class Main {

    public static void main(String[] args) {

        FrameOne frame = new FrameOne();
    }
}

FrameOne class:

    public class FrameOne extends JFrame implements ActionListener{

    private JButton btn1, btn2;

    FrameOne () {

        setVisible(true);
        setSize(400,400);
        setLayout(new FlowLayout());
        setTitle("Main");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        btn1 = new JButton("opens FrameTwo");
        btn2 = new JButton("close FrameTwo");
        btn1.addActionListener(this);
        btn2.addActionListener(this);
        add(btn1);
        add(btn2);
    }

    @Override
    public void actionPerformed (ActionEvent e) {
        if(e.getSource()== btn1) {  
            FrameTow frameTwo = new FrameTwo(); 
        }

        else if(e.getSource()== btn2) ;
        // {???.dispose(); }
    }
}

` Frame2 class:

    public class FrameTow extends JFrame {

    FrameTwo () {

        setVisible(true);
        setSize(400,400);
        setTitle("FrameTwo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocation(400, 400);

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Any of the below solutions will work

frameTwo.dispatchEvent(new WindowEvent(frameTwo, WindowEvent.WINDOW_CLOSING));

OR

frameTwo.setVisible(false);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...