Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructor problem  RSS feed

 
harsh garg
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.awt.*;
import java.awt.event.*;

class firstpract
{
Frame f1=new Frame("my frame");
public static void main(String[] args)
{
new firstpract();
}

firstpract()
{
f1.setSize(200,200);
f1.setVisible(true);
f1.addWindowListener(new a());


}
class a extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

}
Q1: We all know,can't create the constructor for the main class,how this program runs?
Q2:new firstpract(); and how this syntax works for activating the program
 
Greg Charles
Sheriff
Posts: 3015
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure what your first question means. Of course you can create a constructor for the main class. More than one if you want, assuming you make each one take different parameters. Maybe you mean you can't call the constructor from the main() method, but that's perfectly fine too.

As for your second question, constructing, sizing, and making a frame visible makes it appear on the screen. The frame then responds to events in a separate execution thread, so the fact that main() doesn't have any more code doesn't matter. The JVM will wait until the frame closes before shutting down the program. This code explicitly calls System.exit() when the frame closes. That's not strictly necessary in this case, but it does help in some more complex cases, and so it is a good practice to get into.
 
Campbell Ritchie
Marshal
Posts: 55698
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using a Listener for closing events is very old-fashioned code. So is using Frames rather than JFrames. Have you got an old book?

Writing new firstpract() means you create an object of firstpract (that class name ought to have CapitalLetters in) and that is done by executing all the code in the constructor.

I think at the present you are asking basic Java questions rather than GUI questions; that question can be applied to any class.

You are supposed to create a new thread for running GUI code; if you find any Swing class in the API and look at the link labelled "Swing's Threading Policy" it gives two recommended examples.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!