Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

unexpected behavior....help appreciated!!

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have already posted this at other messageboards but no one has replied yet.Is it a boring question or does no one know the answer? Hope a visitor of this messageboard can explain the following to me. It bugs me that I am not sure why it happens.Know the feeling? )
Please look at the following code. It looks like a fairly simple applet but has some behavior that I find strange. As far as i know you should normally be able to make use of an initializer OR initialize a declared field in the init() method. The thing with the applet below though is that when I initialize Insets theInsets within the init() method, the applet won't run. It will when I make use of an initializer. The reason it doesn't run in the first case is because the getInsets method is looked at first and then it can't return theInsets since the value is still null (un-initialized). You can see this happen when you run it and look at the output,since I put some System.out.println lines inthere. More amazingly the getInsets method is even looked at twice before entering the init() method.
I wonder if there is someone that can explain this behavior...It sure is much appreciated !
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyInsetsButton extends JApplet
{
JButton theButton;
Container theContainer;
//Insets theInsets ;
Insets theInsets = new Insets(1,1,1,1);
public void init()
{
System.out.println("inside init()");
//theInsets = new Insets(1,1,1,1);
theButton = new JButton("Press Me");
theButton.addActionListener(new Switcher());
theContainer = this.getContentPane();
theContainer.add(theButton);
}
public Insets getInsets()
{
System.out.println("inside getInsets");
return theInsets;
}
public class Switcher implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
System.out.println("inside Switcher");
theInsets = new Insets(theInsets.top + 2, theInsets.left + 2,
theInsets.bottom + 2, theInsets.right + 2);
invalidate();
validate();
}
}
}
Thanx in advance !
McPatrick
 
Noah Carroll
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
McPatrick,
I answered this in the beginner forum.
Noah Carroll
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic