This is a problem that i am working on is based on inheritance concept. I am having trouble in the action performed portion of the code. The problem is to create an applet that has a button (JButton) labeled “Change”, a red circle and a green square (each 50 pixels across). Each time the button is pressed, the circle grows by 10 pixels and the square shrinks by 10 pixels. Whenever a shape gets too small (less than or equal to 20 pixels across) or too big (greater than or equal to 100 pixels across) it reverses its growth pattern (i.e., if it was shrinking, it now grows, or vice versa.)
[CODE]import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class M006JApplet extends JApplet
implements ActionListener
{
private Button myBtn;
private Circle myCircle;
private Square mySquare;
public void init()
{
Container c = getContentPane();
c.setLayout(new FlowLayout());
myBtn = new Button(“Change”);
c.add(myBtn);
myBtn.addActionListener(this);
myCircle = new Circle(20, 20, 50);
mySquare = new Square(20, 100, 50);
}
public void actionPerformed(ActionEvent event)
{
myCircle.changeSize();
mySquare.changeSize();
repaint();
}
public void paint(Graphics g)
{
myCircle.drawCircle(g);
mySquare.drawSquare(g);
}
}
class Shape
{
private int x, y;
private int diameter;
private boolean grow = true;
public Shape(int xValue, int yValue, int dia)
{
x = xValue;
y = yValue;
diameter = dia;
}
public void setX(int xValue)
{
x = xValue;
}
public int getX()
{
return x;
}
public void setY(int yValue)
{
y = yValue;
}
public int getY()
{
return y;
}
public void setDiameter(int dia)
{
diameter = dia;
}
public int getDiameter()
{
return diameter;
}
public void changeSize()
{ if (grow)
{
radius += 10;
if (radius > 100)
{ grow = false;
}
}
else
{
radius -= 10;
if (radius < 20)
{ grow = true;
}
}
}
}
class Circle extends Shape
{
public Circle(int a, int b, int w)
{
super(a, b, w);
}
public void drawCircle(Graphics g)
{
g.setColor(Color.red);
g.fillOval(super.getX(), super.getY(), super.getDiameter(), super.getDiameter());
g.setColor(Color.black);
g.drawOval(super.getX(), super.getY(), super.getDiameter(), super.getDiameter());
}
}
class Square extends Shape
{
public Square(int a, int b, int w)
{
super(a, b, w);
}
public void drawSquare(Graphics g)
{
g.setColor(Color.green);
g.fillRect(super.getX(), super.getY(), super.getDiameter(), super.getDiameter());
g.setColor(Color.black);
g.drawRect(super.getX(), super.getY(), super.getDiameter(), super.getDiameter());
}
}
Any help greatly apprciated. Again this is a home work problem and i am not asking anyone to do it for me, just a little help as to what logic i would use to get the change button to work as to get the required output.
thanx,
kanaka