Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

.dispose doesn't work on JFrame

843807Mar 8 2010 — edited Mar 8 2010
Hello.

I am having a problem with a JFrame. My program works as follows:
The MainFile constructs a new instance of File1. File1 extends JFrame.
Clicking on the "Open Window" button in File 1 creates a JFrame containing
File2, which is a class that extends JPanel.

To close the window again, there is the "Close Window" button in File1, that
uses the .dispose() method on the JFrame created by File1, but it doesn't work.
The button works fine, but the line that should dispose of the JFrame doesn't seem to do anything.

Thanks in advance,
Any help is greatly appreciated.
-Ulverbeast
import java.awt.FlowLayout;
import javax.swing.JFrame;

public class MainFile {

    /*
     * MainFile.java
     */
    public static void main(String[] args) {
        File1 file1 = new File1();

        JFrame frame = new JFrame("First frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLayout(new FlowLayout());
        frame.setSize(300, 200);
        frame.add(file1);
    }
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class File1 extends JPanel implements ActionListener {

    private JButton openBtn, closeBtn;
    private boolean showWindow = false;

    /*
     * File1.java
     */
    public File1() {

        setSize(200, 200);
        setLayout(new FlowLayout());

        openBtn = new JButton("Open Window");
        openBtn.addActionListener(this);

        closeBtn = new JButton("Close Window");
        closeBtn.addActionListener(this);

        add(openBtn);
        add(closeBtn);

    }

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();

        File2 file2 = new File2();

        JFrame frame = new JFrame("Second frame");
        frame.add(file2);
        frame.setSize(200, 200);
        frame.pack();
        frame.setResizable(false);
        frame.setLocation(500, 500);

        if (source == openBtn && showWindow == false) {
            frame.setVisible(true);
            showWindow = true;
        }

        if (source == closeBtn && showWindow == true) {
            frame.dispose();
            showWindow = false;
        }
    }
}
import java.awt.*;
import javax.swing.*;

public class File2 extends JPanel {

    /*
     * File2.java
     */
    public File2() {

        setSize(200, 200);
        setLayout(new FlowLayout());

        JLabel label = new JLabel("Label");
        add(label);
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 5 2010
Added on Mar 8 2010
3 comments
975 views