Honey
Honey

Reputation: 13

Cannot find symbol in java swing

I am getting compile-time error saying cannot find symbol j.setDefaultCloseOperation

symbol: variable EXIT_ON_CLOSE
location: class Test

Below is my program.

import javax.swing.JFrame;
public class Test{
    public static void main(String[] args) {
        JFrame j=new JFrame();
        j.setSize(900,900);
        j.setVisible(true); 
        j.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

I have searched the web but not able to find correct answer, please help me.

Upvotes: 1

Views: 625

Answers (1)

Thiyagu
Thiyagu

Reputation: 17910

The EXIT_ON_CLOSE is defined as a static final int in JFrame class. If you want to use that, you can do one of the following

  1. JFrame.EXIT_ON_CLOSE i.e, j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  2. Use a static import import static javax.swing.JFrame.EXIT_ON_CLOSE; or import static javax.swing.JFrame.*; (In this case, your existing code will work).

There is also one defined in WindowConstants too. (WindowConstants.EXIT_ON_CLOSE)

IMO, the first option is better as the readers can see exactly from where EXIT_ON_CLOSE comes from (without needing to hover the mouse over it in an IDE or going to the imports section to find that out).

Upvotes: 4

Related Questions