janepe
janepe

Reputation: 99

Extending Graphics class with drawLine(double, double, double, double)

Problem: // where the story begins
The method drawLine(int, int, int, int) in the type Graphics is not applicable for the arguments (double, double, double, double)

g.drawLine((int)10*xi, (int)30*yi, (int)90*xi, (int)30*yi);
// where xi is widthScale and yi is heightScale

as you can see it's crappy

Actual Prototype:
public abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.

What I would like to do:

g.drawLine(double x1, double y1, double x2, double y2);

or

g.drawLine(int x1, int y1, int x2, int y2, double widthScale, double heightScale);

Turn me to right direction and kick my ass.

Upvotes: 3

Views: 1932

Answers (2)

Boann
Boann

Reputation: 50042

You can't really extend Graphics, but you can create a static helper function to do what you need:

static void drawLine(Graphics g, double x1, double y1, double x2, double y2) {
    g.drawLine(
        (int)Math.round(x1), (int)Math.round(y1),
        (int)Math.round(x2), (int)Math.round(y2));
}

The reason that g.drawLine((int)10*xi, (int)30*yi, (int)90*xi, (int)30*yi); does not work is because the typecast has a higher precedence than the multiplication. So (int)10*xi casts 10 to int, and then multiplies it by xi, which is a double again. (An int multiplied by a double is a double.) You could fix it by wrapping the expression in brackets: (int)(10*xi), but it should still be rounded, so making a helper function is a good idea to reduce clutter.

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

No need to "extend" Graphics, and it would not be very useful if you did, since the Swing Graphics engine would not be able to produce objects of your specific class. So this begs the question -- where would you get your specific MyGraphics objects from?

Instead, I'd use a shape object such as Line2D, and construct it with its Line2D.Double subtype, and then draw it with a Graphics2D object. The Graphics2D object can be obtained by casting a Graphics object to this. This is allowed for most Graphics objects, including those used to draw images within JComponents and within BufferedImages. There are a few places where it might not be permissible, but I haven't run into this yet.


Edit
I wonder if your problem is coming from mixing view with model. Perhaps the best solution for your problem is to have your model use doubles, while the view uses ints to display the data held by the model. Somewhere when translating the data from model to view, you would need to round, of course.

Upvotes: 4

Related Questions