FrameOne上的按钮将关闭FrameTwo. ActionListener引用JAVA中另一个类的对象 [英] Button on FrameOne shall close FrameTwo. ActionListener referes object of another class in JAVA

查看:76
本文介绍了FrameOne上的按钮将关闭FrameTwo. ActionListener引用JAVA中另一个类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在单独的类中有两个框架(FrameOne和FrameTwo)FrameOne有两个按钮.一个打开第二个框架,一个打开第二个框架.我知道如何打开FrameTwo.但不是如何从第一帧关闭.如何对其进行编码以使其正常工作?谢谢. (我知道也有类似的问题.我全部都答了.但是它没有给我答案.GUI指南也无济于事.)

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类:

    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类:

    public class FrameTow extends JFrame {

    FrameTwo () {

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

    }
}

推荐答案

以下任何解决方案都可以使用

Any of the below solutions will work

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

OR

frameTwo.setVisible(false);

这篇关于FrameOne上的按钮将关闭FrameTwo. ActionListener引用JAVA中另一个类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆