aspose file tools*
The moose likes Beginning Java and the fly likes java program for sawtooth pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "java program for sawtooth pattern" Watch "java program for sawtooth pattern" New topic
Author

java program for sawtooth pattern

kanaka tam
Ranch Hand

Joined: Jan 19, 2004
Posts: 42
Hello folks,
i am new to java programming. Have a little trouble with this java program that displays sawtooth pattern. I used for loop and put drawString statements inside the loop and executed twice and got the desired output. But the problem is when i resize the applet window the sawtooth disappears. So obviously there is a problem and i couldn't fix it. Can anyone help me with this. I have a condition for my class and that is i should use loops for this program cause i tried doing with methods and invoking methods and works fine but with for loop it is screwy.
This is my code

import java.awt.*;
import java.applet.Applet;

public class Tooth extends Applet
{
private int x = 40;
private int y = 40;

public void paint(Graphics g)
{
for(int i = 0; i < 2; i++)
{
g.drawString("S", x, y);
y = y + 15;
g.drawString("SS", x, y);
y = y + 15;
g.drawString("SSS", x, y);
y = y + 15;
g.drawString("SSSS", x, y);
y = y + 15;
g.drawString("SSSSS", x, y);
y = y + 15;
}

}

}
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

x and y are member variables and get initialized only once, when the applet is created. The "paint" method changes their values. The second time "paint" is called, x and y aren't at their beginning values, but at the values where "paint" left them the first time. Therefore the drawing shows up offscreen where it's invisible.

The best solution would be to make x and y local variables declared inside "paint". Then they'd be initialized each time "paint" was called.


[Jess in Action][AskingGoodQuestions]
kanaka tam
Ranch Hand

Joined: Jan 19, 2004
Posts: 42
Thank you Ernest. I did that and now it works fine..
kanaka
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: java program for sawtooth pattern