How to draw a dashed line, a dashed rectangle, and a dashed polygon in Java?

Experts Exchange Solution brought to you by

Enjoy your complimentary solution view.

Get every solution instantly with Premium.
Start your 7-day free trial.

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

All I need is a simple dot line. Can you just post me a source instead?

Thanks in advance!

Let me know if you find this satisfactory and I will post it as an answer. If not, let me know what else you need.

/* draw blue spots at each mouse click, red spots at doubleclicks */

import java.awt.Graphics;

import java.awt.Color;

import java.awt.Event;

import java.awt.Point;

public class Lines extends java.applet.Applet {

final int MAXLINES = 10;

Point starts[] = new Point[MAXLINES]; // starting points of past lines

Point ends[] = new Point[MAXLINES]; // starting points of end lines

Point anchor; // start of current line

int currline = 0; // number of lines

Point currentpoint; // current end of line

public void init() {

setBackground(Color.white)

}

public boolean mouseDown(Event evt, int x, int y) {

if (currline < MAXLINES)

anchor = new Point(x,y);

else System.out.println("Too many lines");

return true;

}

public boolean mouseUp(Event evt, int x, int y) {

if (currline < MAXLINES)

addline(x,y);

else System.out.println("Too many lines");

return true;

}

public boolean mouseDrag(Event evt, int x, int y) {

if (currline < MAXLINES) {

currentpoint = new Point(x,y);

repaint();

}

return true;

}

void addline(int x,int y) {

starts[currline] = anchor;

ends[currline] = new Point(x,y);

currline++;

currentpoint = null;

anchor = null;

repaint();

}

boolean flag;

int count;

int sign(int val){

if (val > 0 ) return 1;

if (val == 0) return 0;

return -1;

}

void drawDotLine(int x1, int y1, int x2, int y2, int thickness, Graphics g){

flag = true;

count = 0;

double x,y;

float deltaX, deltaY;

int Length;

if (Math.abs(x2 -x1) >= Math.abs(y2 -y1))

Length = Math.abs(x2 - x1);

else

Length = Math.abs(y2 - y1);

deltaX = (float)(((float)x2 - (float)x1) / (float)Length);

deltaY = (float)(((float)y2 - (float)y1) / (float)Length);

x = (float)x1 + 0.5 * (float)sign((int)deltaX)*d

y = (float)y1 + 0.5 * (float)sign((int)deltaY)*d

int i = 1;

while (i++ <= Length){

if (flag){

g.fillOval((int)x, (int)y, thickness + 1, thickness + 1);

count++;

if (count == thickness + 1){

flag = false;

count = 0;

}

}

else{

count++;

if (count == thickness + 1){

flag = true;

count = 0;

}

}

x += deltaX;

y += deltaY;

}

g.fillOval((int)x, (int)y, thickness + 1, thickness + 1);// Insure the endpoint is also drawn

}

public void paint(Graphics g) {

// Draw existing lines

for (int i = 0; i < currline; i++) {

drawDotLine(starts[i].x, starts[i].y,

ends[i].x, ends[i].y, 1, g);

}

// draw current line

g.setColor(Color.blue);

if (currentpoint != null)

drawDotLine(anchor.x,ancho

}

}

The following code will generate a dashed line:

int sign(int val){

if (val > 0 ) return 1;

if (val == 0) return 0;

return -1;

}

void drawDotLine(int x1, int y1, int x2, int y2, int thickness, Graphics g){

flag = true;

count = 0;

double x,y;

float deltaX, deltaY;

int Length;

if (Math.abs(x2 -x1) >= Math.abs(y2 -y1))

Length = Math.abs(x2 - x1);

else

Length = Math.abs(y2 - y1);

deltaX = (float)(((float)x2 - (float)x1) / (float)Length);

deltaY = (float)(((float)y2 - (float)y1) / (float)Length);

x = (float)x1 + 0.5 * (float)sign((int)deltaX)*d

y = (float)y1 + 0.5 * (float)sign((int)deltaY)*d

int i = 1;

while (i++ <= Length){

if (flag){

g.fillOval((int)x, (int)y, thickness + 1, thickness + 1);

count++;

if (count == thickness + 1){

flag = false;

count = 0;

}

}

else{

count++;

if (count == thickness + 1){

flag = true;

count = 0;

}

}

x += deltaX;

y += deltaY;

}

g.fillOval((int)x, (int)y, thickness + 1, thickness + 1);// Insure the endpoint is also drawn

}

For a rectangle, you would use:

void dotRectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int thickness, Graphics g){

// You could always use the Point class to use less parameters

drawDotLine(x1, y1, x2, y2, thickness, g);

drawDotLine(x2, y2, x3, y3, thickness, g);

drawDotLine(x3, y3, x4, y4, thickness, g);

drawDotLine(x1, y1, x4, y4, thickness, g);

}

For a Polygon, pass a Vector of points, use an enumeration over the vector to extract the points and draw the lines from the last point extracted to the one being extracted from the vector.

Keep a reference to the first foint extracted fromt the vector so that when you break out of the enumeration you can draw a line from the last point to the first.

Let me know if you have problems implementing this and I'll write the code and post it in a comment.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Java

From novice to tech pro — start learning today.

Experts Exchange Solution brought to you by

Enjoy your complimentary solution view.

Get every solution instantly with Premium.
Start your 7-day free trial.

This does not men it can't be done though. It only means you wil have to do it yourself.

To obtain dashed, and other types)of lines, you will have to completley override the implementations of drawLine. I'm not sure if drawRect and drawPolygons call the line method or the underlying OS's equivalent functions, so you migh have to override those as well.

The basic line drawing algorithm is called DDA (Digital Diferential Analyzer) and works as follows:

Define a function called Sign that returns -1, 0, 1 as its argument is <0, =0, >0

DDA: Params: x1,y1,x2,y2 are the end points of the line

//aproximate the line length

if abs(x2-x1) >= abs(y2-y1)

Length = abs(x2 -x1)

else

Length = abs(y2 - y1)

endif

// select the larger of deltaX or deltaY to be one rater unit

deltaX = (int)( ((x2 -x1)/Length) +0.5)

deltaY = (int) (( (y2 - y1)/Length +0,5) // round the values rather than flooring

x = x1 + 0.5*Sign(deltaX)

y = y1 + 0.5*Sign(deltaY)

i = 1

while (i <= Length){

Plot((int) (x), (int) (y))

x += deltaX

y += deltaY

I+=1

}

finish.

The Plot function also, has no equivalent in Java (unless you count a buggy and messy setPixelGrabber) so you would have to make a call to the original line with super((Int)(x), (int) (y),(Int)(x), (int) (y)) to duplicate the funcionality.

Once you have the code up and running, you can add a counting variable to determine the number of pixels that have been painted. If you compare this number with a dash-lenght constant, you can then set an if statement to avoid painting the next dash-length points:

while (i <= Length){

if (points < dashlen){

if (drawFLag)

Plot((int) (x), (int) (y))

points++;

}

else{

drawFlag = !drawFlag;

points = 0;

}

x += deltaX

y += deltaY

I+=1

}

In this fahion, you can control line width (by placing pixels above/below or left/right of the calculated dot depending on slope), and diferent types of dasshed lines (dot, dot-slash, etc).

I have succesfuly implemented this algorithm over the yeras in Fortran, Pascal, PL/I, C and C++ (at those times when graphics libraries were not yet available for the platforms I was working with :-)) but have not yet required to do it in Java. Reason for which I didn't just post you the source.

Regarding rectangle and polygon, if your lucky, Java will call drawLine internaly to build the figures, otherwise, implementing them is rather trivial, just call your overriden drawLine (or drawDashedLine if you opted to use your own method) to generate the figures.

One final point: overriding drawLine would require that the code you wrote contain a flag that called the original method by default, and the dashed line when the flag is set (the flag can be an int value > 0 if you intend to support multiple dash styles). If you only intend to support a single dash style, it would perhaps be eysier to simply add a method rather than overriding.