简体   繁体   中英

Closing a JFrame window?

I'm using two frames. In the first frame I have a button to open the second frame. In the second frame there is also a button, but this one is for closing the second frame. But I don't know how to do this, and I'm looking for some help to solve this?

GUI1

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 extends JFrame implements ActionListener{
JButton btn1;
Container contentPane;
public GUI1()
{
    setTitle("GUI 1");
    setResizable(false);
    setSize(600,300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout());
    btn1 = new JButton("Open GUI 2 frame");
    contentPane.add(btn1);
    btn1.setFocusable(false);
    btn1.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
    if(event.getSource() == btn1)
    {
        GUI2 frame2 = new GUI2();
        frame2.setVisible(true);
    }
}
public static void main(String[] args) {
    GUI1 frame = new GUI1();
    frame.setVisible(true);
}
}

GUI2

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI2 extends JFrame implements ActionListener {
Container contentPane;
JButton btn2;
public GUI2()
{
    setTitle("GUI 2");
    setResizable(false);
    setSize(400,200);
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout());
    btn2 = new JButton("Close GUI 2 frame");
    contentPane.add(btn2);
    btn2.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
    if(event.getSource() == btn2)
    {
        // Close GUI2 ??
    }
}
}

Simply call dispose() in the listener:

public void actionPerformed(ActionEvent event){
    if(event.getSource() == btn2)
    {
        dispose();
    }

Also, by clicking X, this will dispose the window since you have set the defaultCloseOperator(DISPOSE_ON_CLOSE);

Your contentPane has a method called remove (or removeAll if you'd like to remove all the frames). contentPane.remove(this) should probably work.

你只调用方法dipose()

You need a reference to your instance of GUI1 in GUI2. So maybe add a private variable private GUI1 firstGUI in your GUI2 class. Then write a setter method public void setGUI1(GUI1 myFirstGUI){ this.firstGUI = myFirstGUI; } public void setGUI1(GUI1 myFirstGUI){ this.firstGUI = myFirstGUI; } .

Then you should set the GUI1 variable from the outside with this setter.

And then you can call firstGUI.dispose() in your actionPerformed Method for btn2.

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