Hi,
I'm trying to create an 8x8 chessboard using GeneralPath. I've been able to make the outline of the "matrix" itself, but I am having trouble filling it. I've tried filling it with both windingrules, so I guess my question is as follows: Is there any way I can make the board I've created using a path into one whole figure which allows me to fill every other square with the color black?
My code:
import java.awt.*; import javax.swing.*; import java.awt.geom.*; public class chessBoard extends JApplet{ public static void main (String []args) { JFrame frame = new JFrame(); frame.setTitle("Chessboard"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JApplet applet = new chessBoard(); applet.init(); frame.getContentPane().add(applet); frame.pack(); frame.setVisible(true); } public void init() { JPanel panel = new chessBoardPanel(); getContentPane().add(panel); } } class chessBoardPanel extends JPanel { public chessBoardPanel() { setBackground(Color.white); setPreferredSize(new Dimension(600, 400)); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); g2.setColor(Color.black); int w = this.getWidth(); int h = this.getHeight(); float x0 = 0.1f*w; float y0 = 0.1f*h; float y = y0; float x = x0; path.reset(); for (int i = 0; i <= 8; i++) { path.moveTo(x, y0); path.lineTo(x, h - y0); x += x0; } for (int i = 0; i <= 8; i++) { path.moveTo(x0, y); path.lineTo(w - x0, y); y += y0; } path.closePath(); g2.draw(path); } }
What I've done is created 9 lines vertically and horizonally, merging into an 8x8 matrix.
I've also tried adding this after I'm done drawing with"path":
AffineTransform tr = new AffineTransform(); Shape pathshape; path.setWindingRule(GeneralPath.WIND_EVEN_ODD); pathshape = (Shape)tr.createTransformedShape(path); g2.draw(pathshape);
Current output:
Very grateful for any response.
Best regards
Ole Martin