CONTENTS | PREV | NEXT | Java 2D API |
A custom line style such as a complex dashing pattern can easily be created using a BasicStroke object. When you create a BasicStroke object, you can specify two parameters that control the dashing pattern:
In the following example, a line is drawn using two different dashing patterns. In the first, the size of the dashes and the space between them is constant. The second dashing pattern is more complex, using a six-element array to define a dashing pattern that looks like:Both dashing patterns use a dash phase of zero, causing the dashes to be drawn starting at the beginning of the line.
float dash1[] = {10.0f};
BasicStroke bs = new BasicStroke(3.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
g2.setStroke(bs);
Line2D line = new Line2D.Float(20.0f, 10.0f, 100.0f, 10.0f);
g2.draw(line);
float[] dash2 = {6.0f, 4.0f, 2.0f, 4.0f, 2.0f, 4.0f};
bs = new BasicStroke(3.0f, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash2, 0.0f);
g2.setStroke(bs);
g2.draw(line);