I am writing a program that displays Hadamard pattern using recursion.
A 1-by-1 Hadamard pattern is a single black square. In general a 2N-by-2N Hadamard pattern is obtained by aligning 4 copies of the N-by-N pattern in the form of a 2-by-2 grid, and then inverting the colors of all the squares in the lower right N-by-N copy.
I would like to produce the same picture as this one
My code is:
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Hadamard extends JPanel{
@SuppressWarnings("unused")
private void hadamard(Graphics g, int n, int x, int y, int width, int height){
if(n == 0){
g.fillRect(x/2, y/2, width, height);
return;
}
else{
hadamard(g, n-1, x, y, width/2, height/2);
hadamard(g, n-1, x + width, y, width/2, height/2);
hadamard(g, n-1, x, y + height, width/2, height/2);
g.setColor(Color.WHITE);
hadamard(g, n-1, x + width, y + height, width/2, height/2);
g.setColor(Color.BLACK);
}
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
hadamard(g, 2, getWidth() / 2, getHeight() / 2, getWidth() / 2, getHeight() / 2);
}
public static void main(String[] args) {
Hadamard panel = new Hadamard();
JFrame app = new JFrame();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.add(panel);
app.setSize(516, 538);
app.setVisible(true);
}
}
I don’t change properly the colors of the squares in the lower right corner. I’ve been stuck at this step for the last a couple of hours and am hoping someone would give me an idea how to do it correctly because I don’t know.
Thank you in advance.
Nath
Your code is not inverting the lower-right quadrant, it’s simply forcing it to be white.
I would say that the best solution is to add an extra parameter to your recursive method (let’s call it
b), whose value can betrueorfalse. You can then recurse as:Then when you get to the
fillRectcalls, choose white or black depending on the value ofb.