Hi I want to draw a stroke line starting from point (x1,y1)to another point (x2,y2)
If any help .

Dani AI

Generated

Good pointers from and well spotted by — the Java2D BasicStroke plus Graphics2D is the standard way to control width, end caps, joins and dashes for a line. The compact recipe below shows a safe painting pattern for Swing and a few practical tips to avoid common rendering problems.

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create(); // isolate state
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    float[] dash = {10f, 6f}; // dashed pattern (on, off)
    g2.setStroke(new BasicStroke(3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10f, dash, 0f));

    // draw from (x1,y1) to (x2,y2) -- use Line2D for double precision
    g2.draw(new Line2D.Double(x1 + 0.5, y1 + 0.5, x2 + 0.5, y2 + 0.5));

    g2.dispose();
}

Troubleshooting and tips:

  • Always paint on the Event Dispatch Thread and override paintComponent (not paint) in a JPanel; call super.paintComponent(g) first. See the Swing painting tutorial for details.
  • Use g.create() and dispose() to avoid mutating the caller Graphics state.
  • For crisp 1-pixel lines, offset coordinates by 0.5 when painting on integer-based devices; otherwise anti-aliasing may blur thin lines.
  • Stroke width and dash lengths are in user space and are affected by any Graphics2D transform (scaling/rotation) — scale carefully.
  • For problematic joins on sharp angles, change the join style (JOIN_BEVEL) or increase the miter limit.

Reference material: BasicStroke JavaDoc provides all stroke parameters and behavior (BasicStroke javadoc). The Swing painting guide covers proper painting practices (Painting in AWT and Swing).

Recommended Answers

All 2 Replies

Here is Java Sun tutorial on basic shapes

I have got the solution from the linked web
that is using the class
BasicStrok()
thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.