Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

applet&buttons

 
g krishnan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi this prints 1 button with label "Ok" and 4 buttons with label "cancel", pls explain, thanks.

import java.applet.*;
import java.awt.*;
public class Q16 extends Applet {
Button okButton = new Button("Ok");
public void init()
{
add(okButton);
add(okButton);
add(okButton);
add(okButton);
add(new Button("Cancel"));
add(new Button("Cancel"));
add(new Button("Cancel"));
add(new Button("Cancel"));
setSize(300,300); }
}
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because okButton was only created once while you are creating 4 new cancel buttons (they all are added with the keyword new.)
Bill
 
g krishnan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi bill,
can't we add a same button again, for any no.of times we want.
thanks
 
Winfried Gottschalk
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about that:
if java would allow that you add one button object more than once to a panel what do you think would happen if you put an event lister to the botton object.
wingo
 
g krishnan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wingo thanks for that, this clarifies.
 
Parimala Somasundaram
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think one way of explaining this is that every instance that you create creates an object. Since there is only one instance of okButton, it appears only once, whereas 4 instances of 'cancel' are created everytime you call the constructor using 'new'; hence the four cancel buttons.
Originally posted by g krishnan:
hi this prints 1 button with label "Ok" and 4 buttons with label "cancel", pls explain, thanks.

import java.applet.*;
import java.awt.*;
public class Q16 extends Applet {
Button okButton = new Button("Ok");
public void init()
{
add(okButton);
add(okButton);
add(okButton);
add(okButton);
add(new Button("Cancel"));
add(new Button("Cancel"));
add(new Button("Cancel"));
add(new Button("Cancel"));
setSize(300,300); }
}

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic