Instead of long constructor parameter lists, you should consider writing helper methods to let users of your class change the values of attributes. A helper method that modifies the value of an attribute is called a setter method.
First, let's add a setter method to allow Window objects to change their dimensions:
public void setDimensions(int w, int h) {
width = w; // Update attributes with new values passed in
height = h;
}
Let's also add a setter method to allow Window objects to change their frame color:
public void setFrameColor(Color c) {
frameColor = c;
}
You should write as many setter methods as it takes to cover all the attributes.
Here is our final Window class complete with setter methods:
public class Window {
// Attributes
int xPos;
int yPos;
int width;
int height;
Color frameColor;
Color interiorColor;
DrawingTool pencil;
// Constructors
public Window(int x, int y, SketchPad pad) {
// Use the constructor parameters to initialize the xPos, yPos, and pencil attributes
xPos = x;
yPos = y;
pencil = new DrawingTool(pad);
// Choose default values for the rest of the attributes
width = 100;
height = 100;
frameColor = Color.BLACK;
interiorColor = new Color(255, 255, 0);
}
// Methods
public void draw() {
pencil.up(); // Move to window location
pencil.move(xPos, yPos);
pencil.setDirection(90);
pencil.down();
pencil.setColor(interiorColor); // Change color before drawing interior of window
pencil.fillRect(width, height); // Draw interior of window
pencil.setColor(frameColor); // Change color before drawing outer frame of window
pencil.drawRect(width, height); // Draw the window
pencil.forward(height/2);
pencil.backward(height);
pencil.forward(height/2);
pencil.turnRight(90);
pencil.forward(width/2);
pencil.backward(width);
}
// Setter Methods
public void setPosition(int x, int y) {
xPos = x; // Update location attributes
yPos = y;
}
public void setDimensions(int w, int h) {
width = w; // Update dimension attributes
height = h;
}
public void setFrameColor(Color c) {
frameColor = c;
}
public void setInteriorColor(Color c) {
interiorColor = c;
}
}
Last modified: September 05, 2023
Back to Methods