Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Was JFrame disposed?

Tags:

java

swing

jframe

I've got an application with several JFrame window.

My main JFrame wants to know if another JFrame is already disposed.

Which method shall I call to decide?

like image 496
principal-ideal-domain Avatar asked Dec 09 '15 17:12

principal-ideal-domain


People also ask

What is dispose in JFrame?

JFrame.dispose() public void dispose() Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.

Is Java Swing still developed?

Oracle will continue developing Swing and AWT in Java SE 8 and Java SE 11 (18.9 LTS). This means they will be supported by Oracle through at least 2026.

What does dispose () do in Java?

The Dispose() method The Dispose method performs all object cleanup, so the garbage collector no longer needs to call the objects' Object.

Is frame and JFrame same?

A Frame is an AWT component whereas a JFrame is a Swing component.


1 Answers

Although you should probably avoid the use of multiple JFrames, isDisplayable() is a method you could use for this.

Example:

enter image description here

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Example {

    public Example() {
        JFrame frame = new JFrame("Frame 1");
        JFrame frame2 = new JFrame("Frame 2");

        JLabel label = new JLabel("");

        JButton button = new JButton("Check");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText(frame2.isDisplayable() ? "Active" : "Disposed");
            }
        });

        JPanel panel = new JPanel();
        panel.add(button);
        panel.add(label);

        frame.setContentPane(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 100);
        frame.setVisible(true);

        frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame2.setSize(200, 100);
        frame2.setLocation(frame.getX() + frame.getWidth(), frame.getY());
        frame2.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Example();
            }
        });
    }
}
like image 94
Lukas Rotter Avatar answered Oct 05 '22 23:10

Lukas Rotter