Re: Applet, not change color!
michael_jd wrote:
This code works fine, but it does not seem to change the color when
requested. Thanks in advance
for any help
import java.awt.*;
public class Pattern
// change the line above to
public class Pattern extends Canvas
{
private int width,x,y;
private Color hColor, vColor;
public Pattern(int x, int y, int width, Color hColour, Color
vColour)
{
this.width = width;
this.x = x;
this.y = y;
this.hColor = hColor;
this.vColor = vColor;
}
public void draw(Graphics g)
// change the line above to
public void paint(Graphics g)
{
int origionalX = x, origionalY = y;
int xGap = width/10;
int yGap = width/10;
for(int i = 0; i < 10; i++)
{
g.setColor(hColor);
g.drawLine(x,y,x + width,y);
y += yGap;
}
x = origionalX;
y = origionalY;
for(int i = 0; i < 10; i++)
{
g.setColor(vColor);
g.drawLine(x,y,x,y + width);
x += xGap;
}
x = origionalX;
y = origionalY;
g.drawRect(x,y,width,width);
}
}
import java.applet.Applet;
public class Quilt extends Applet
{
// change the init method to
public void init() {
Pattern pat = new Pattern(10,10,50,Color.BLUE,Color.GREEN);
pat.setSize(400,300);
add(pat);
}
public void init()
{
;
}
// lose the paint method completely in Quilt, you don't need it
public void paint(Graphics g)
{
Pattern p = new Pattern(10,10,50,Color.green,Color.blue);
p.draw(g);
}
}
As Andrew said, consider using an application instead of an applet to
learn your programming. They are much easier to test, no browser or
appletviewer, and you can readily adapt a component to be displayed in
an applet. Consider the application version of your program below that
I wrote. You could easily add the parameters to the constructor and
then use the test class in an applet.
import java.awt.*;
import java.awt.event.*;
public class test extends Canvas {
int width = 400;
int height = 300;
public test() {
setSize(width,height);
}
public void paint(Graphics g) {
g.setColor(Color.BLUE);
for (int i=0; i<width; i+=10)
g.drawLine(i,0,i,height);
g.setColor(Color.RED);
for (int i=0; i<height; i+=10)
g.drawLine(0,i,width,i);
}
public static void main(String[] args) {
Frame f = new Frame();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
test t = new test();
f.add(t,BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
}
--
Knute Johnson
email s/nospam/knute/