0

I am currently trying to draw a line and keep the line proportionally the same no matter how the user resizes the JFrame. However, the problem I run into is when I try to draw a line when the user makes the JFrame smaller than the default value, as I end up multiplying the coordinates by fractions under 1, and since g2.drawLine() requires integers, it takes them as 0's and nothing is drawn. I'm wondering if there's a work-around to this little glitch or if you guys have any suggestions of how I should change my logic.

  • FYI: Beware of re-posting a question you've not gotten an answer to yet - it's not really encouraged. I might take a few days before you get an answer you're satisfied with – MadProgrammer Apr 04 '18 at 00:26
  • @MadProgrammer it's not the same question - the previous one was when I had no clue how to do this, but this one is me having problems with one of the ways of implementations I tried out –  Apr 04 '18 at 01:05

2 Answers2

0

I think what you're seeing is just because of integer division. See Why is the result of 1/3 == 0?. When you have (width / 624), the result of this is always 0 if width is less than 624.

You could:

  • use (width / 624.0), which performs the division in floating-point (as double), or
  • you could rearrange your parentheses to be e.g. (int) ((x * width) / 624)) instead of (int) (x * (width / 624)).

However, to answer the question directly, you can draw a line with floating-point coordinates by using java.awt.geom.Line2D:

Line2D line2D = new Line2D.Double(x1, y1, x2, y2);
graphics2D.draw(line2D);

(Also see https://docs.oracle.com/javase/tutorial/2d/geometry/primitives.html.)

Radiodef
  • 35,285
  • 14
  • 78
  • 114
0

multiplying the coordinates by fractions under 1, and since g2.drawLine() requires integers, it takes them as 0's

That's obviously false! If a coordinates is say, 327, then multiplying it by say 0.7 gives 228.9. That's not an integer but is has integer part, so you can safely convert it to integer:

double factor = ...;
int newCoord, oldCoord = ...;
newCoord = (int)(oldCoord * factor)

will give you the rounded result.

Or something else is wrong...

Jean-Baptiste Yunès
  • 30,872
  • 2
  • 40
  • 66