I am having problem testing my overridden paint components.
I have removed a lot the code to simplify things
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.RED);
int y = //some come;
int height = //some code
//for loop
g.clearRect(1, y, getWidth(), height);
g.drawRect(1, y, getWidth(), height);
}
}
super.paintComponent(g);
}
My paint component creates multiple rectangles. I need to get details on the number of rectangles drawn and their height. I'm not sure how to make a unit test to do this.
I've tried to use the TextAreas' getComponents()
method but it returns null. I thought calling repaint() would trigger the paint component to execute.
Thanks for any help
There are 2 solutions I can think of:
Call your component's paint
method with the Graphics
from a BufferedImage
. So,
BufferedImage bi = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
yourComponent.setSize(width,height);
yourComponent.paint(g2);
g2.dispose();
Analyse the contents of bi
.
Option 2, you can make your component expose what it has painted. As your rectangles are drawn, record what calls you make. Then make that available from the object. This may be more useful if you need specific dimensions.
private StringBuilder sb = new StringBuilder();
public String getOperations() {
return sb.toString();
}
@Override
protected void paintComponent(Graphics g) {
sb.setSize(0);
g.setColor(Color.RED);
sb.append("Color(red),");
int y = //some come;
int height = //some code
//for loop
g.clearRect(1, y, getWidth(), height);
sb.append("Clear(").append(getWidth()),append(",")
.append(height).append("),");
g.drawRect(1, y, getWidth(), height);
sb.append("drawRect(").append(1),append(","),append(y).append(",")
.append(getWidth()),append(","),append(height).append("),");
g.dispose();
super.paintComponent(g);
}
It says there are no components even though I do g.drawRect(1, y, getWidth(), height);
You are not adding components to the panel so there are no components to get. The drawRect(...) method only draws the outline of a rectangle, it does not create a component.
If you want to keep track of the "rectangle shapes" that you draw then use an ArrayList to store information about the shapes. See the DrawOnComponent
example from Custom Painting Approaches for an example that uses an ArrayList.