public class MandlebrotSet extends JFrame
{
private DrawingPane dPane = new DrawingPane();
public MandlebrotSet()
{
//Add the DrawingPane object to the frame.
add(dPane);
dPane.repaint();
}
class DrawingPane extends JPanel
{
// Create the BufferedImage object.
// (I didn't know what to use for the last argument, and evidently from the stack trace the exception originates here)
private BufferedImage mandlebrot = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// Find the center of the component.
int shiftx = getWidth() / 2;
int shifty = getHeight() / 2;
// Start from the top-left of the component.
Point p = new Point(0, 0);
// Plot from top-to-bottom left-to-right.
// (Section adapted from the pseudocode on the Wikipedia page: http://en.wikipedia.org/wiki/Mandlebrot_set).
while(p.y <= getHeight())
{
while(p.x <= getWidth())
{
//Adjust for calculating the point series.
int x = p.x - shiftx;
int y = shifty - p.y;
//Set the bounds for iterating.
int iterationnum = 0;
int maxiteration = 1000;
//Calculate the series of points.
while (x*x + y*y <= (2*2) && iterationnum < maxiteration)
{
int xtemp = x*x - y*y + p.x;
y = 2*x*y + p.y;
x = xtemp;
iterationnum++;
}
// If the point series did not escape the bounds within the number of iterations, paint the point black, else cyan.
// (I'm considering expanding beyond the binary coloring system. This would simply be a matter of chaining if-else-if statements, right?)
if(iterationnum == maxiteration)
{
g.setColor(Color.BLACK);
}
else
{
g.setColor(Color.CYAN);
}
// Plot the point.
plot(p.x, p.y, g.getColor());
p.x++;
}
// Increment y and start from the left again.
p.y++;
p.x = 0;
}
// Draw the image.
// (I'm unfamiliar with the proper implementation of this. Does this seem right?)
g.drawImage(mandlebrot, 0, 0, Color.GREEN, this);
}
private void plot(int xpoint, int ypoint, Color c)
{
mandlebrot.setRGB(xpoint, ypoint, c.getRGB());
}
}
}