samsri
samsri

Reputation: 1104

Can setDefaultCloseOperation work without specifying any object?

I came across a code which calls setdefaultcloseoperation() without reference to any object. I read that methods are called with reference to object. Here is the code

public class Mainpage extends JFrame implements ActionListener{
    JFrame f = new JFrame("Mainpage");

    public Mainpage() {
        super("Mainpage");
        f.setSize(1000,6000);
        f.getContentPane().setLayout(null);
        f.setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE); // how is this happening?
}

I want to know how setDefaultCloseOperation(EXIT_ON_CLOSE); is working. Thanks.

Upvotes: 1

Views: 1214

Answers (2)

Reimeus
Reimeus

Reputation: 159844

The method setDefaultCloseOperation refers to the current instance of JFrame.


Some side notes:

1) The second JFrame f is unnecessary here:

public class Mainpage extends JFrame implements ActionListener{

public Mainpage(){
   super("Mainpage");
   setSize(1000,6000);
   ...
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   setVisible(true);
}

2) Avoid using the null layout. See Doing Without a Layout Manager.

Upvotes: 4

Lews Therin
Lews Therin

Reputation: 10995

Well you extended JFrame. So in essence you are doing this.setDefaultOperation(EXIT_ON_CLOSE).

Also it doesn't make sense that you are creating a JFrame inside a JFrame.. unless this was an experiment of yours. Simple answer would be don't extend JFrame, and use f.setDefaultOperation(EXIT_ON_CLOSE).

Upvotes: 4

Related Questions