Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt related to applet and frames

 
Maya Nair
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried the following code taken from some mock exam:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class hello extends Applet
{
public void init()
{
add(new myButton("BBB"));
}
public void paint(Graphics g){}
class myButton extends Button
{
myButton(String label)
{
super(label);
}
public String paramString()
{
return super.paramString();
}
}
public static void main(String a[])
{
Frame myFrame=new Frame("Frame1");
myFrame.setSize(300,100);
Applet myapplet=new hello();
Button b=new Button("My Button");
myapplet.add(b);
b.setLabel(b.getLabel()+"New");
myButton b1=(new hello()).new myButton("ParamButton");
System.out.println(b1.paramString());
myFrame.add(myapplet);
myFrame.setVisible(true);
myFrame.addWindowListener(new WindowAdapter (){
public void windowClosing(WindowEvent e){
System.exit(0);} });
}
}// class hello ends
The above code when run as a standalone Application returns only one button ("MyButtonNew")
Why doesnt the other button("BBB") initialised in the applet appear?
One more thing, when u compile the class hello.java the following files are generated.
1)hello.class,
2)hello$myButton.class,
3)hello$1.class
The first two are understood but why the third one???
Could anyone please explain me as soon as possible??I am planning to give JCP by end of this Jan.
 
Zheng Huang
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
appletviewer does not run main(). hello$1.class file was created because of new WindowAdapter (). Let me know if I am wrong.
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Maya,
When you run the code as an application vs an Applet you must explicitly call the Applet <code>init()</code> method.

Re-compile and run. You will see both buttons.
When you load an Applet in a browser, it handles the call to <code>init()</code>. When you load it from an application, your code must replicate the functionality provided by the browser.
Hope that helps.
Jane
 
Maya Nair
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jane,
That means if I run the code as an application then applets
init() wont get called,the class hello's constructor will be called which in this case will be default no-arg constr.
Actually I was under the impression that when u execute the line
Applet myapplet= new hello();it will first execute init() method of the applet and then continue further...but since init() is called by the browser,things are simpler.
now I got it!!
Thanks for the explaination.
Maya
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic