Java AWT Graphics2D draw dashed line

Introduction


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  Random rnd = new Random();
  @Override//w  ww  . java  2s .  c  om
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    
    Graphics2D g2d = (Graphics2D) g;
    g2d.setBackground(Color.BLACK);
    g2d.clearRect(0, 0, getParent().getWidth(), getParent().getHeight());
    
    // Red line
    g2d.setPaint(Color.RED);
    // 5 visible, 5 invisible
    final float dash[] = {5, 5};
    // 10 thick, end lines with no cap, 
    // any joins make round, miter limit,
    // dash array, dash phase
    final BasicStroke dashed = new BasicStroke(10, BasicStroke.CAP_BUTT,  
            BasicStroke.JOIN_ROUND, 0, dash, 0);
    
    g2d.setStroke(dashed);
    g2d.drawLine(100, 10, 10, 110);
  }

  public static void main(String[] args) {
    // create frame for Main
    JFrame frame = new JFrame("java2s.com");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Main Main = new Main();
    frame.add(Main);
    frame.setSize(300, 210);
    frame.setVisible(true);
  }
}
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  @Override/*  w w  w  . ja va 2s .  c om*/
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g; // cast g to Graphics2D

    // draw 2D line using stroke
    float[] dashes = { 10 }; // specify dash pattern
    g2d.setPaint(Color.YELLOW);
    g2d.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10, dashes, 0));
    g2d.draw(new Line2D.Double(320, 30, 395, 150));
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("Drawing 2D shapes");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Main Main = new Main();
    frame.add(Main);
    frame.setSize(425, 200);
    frame.setVisible(true);
  }
}



PreviousNext

Related