Use dashed stroke to draw dashed line in Java
Description
The following code shows how to use dashed stroke to draw dashed line.
Example
//from w w w .jav a2 s . c o m
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
float[] dash1 = { 2f, 0f, 2f };
g2d.drawLine(20, 40, 250, 40);
BasicStroke bs1 = new BasicStroke(1,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND,
1.0f,
dash1,
2f);
g2d.setStroke(bs1);
g2d.drawLine(20, 80, 250, 80);
}
}
public class Main {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 450, 450);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
The code above generates the following result.