tags:

views:

78

answers:

3

I know this is gonna be a stupid question. Pardon me as a n00b into CS

I have a new swing component that inherits from JComponent. I am trying to paint lines on its surface to show that the lines split the control into equal parts. The code looks like

int spc;
spc = (int) Math.round((this.ZBar.getWidth() / this.ZBar.getModel().getModelSize()));

        for (int i = 0; i <= this.ZBar.getModel().getModelSize(); i++) {
            g.drawLine(i * spcing, 0, i *, this.ZBar.getHeight());

        }

this.ZBar.getModel().getModelSize(); gives out number of parts to split into. However, in some cases there is some more space left on the right most end of my component. I guess it is gue to the Type conversion done by Math.round. How can I solve this ??

A: 

The code you posted will not compile due to syntax errors, but I see no immediate problems with your approach. You said that the problem shows up intermittendly. This suggests the problem might lay with the way swing does refreshing, and how you handle that in your code. Try reading up on that.

Internet Friend
+1  A: 

It is because that division is a int type divide. For example:

5 / 2 == 2

Math.round is doing nothing here. It is already being rounded (as Math.floor instead).

To get your intended effect, cast the int to a double before the division:

(double)5 / 2 == 2.5

Or in your specific case:

spc = (int) Math.round(((double)this.ZBar.getWidth() / this.ZBar.getModel().getModelSize()));
Nick Whaley
A: 

Thank you very much for the reply. Solved this.

I have made all those integer mess to double. Then used Java2D package to handle doubles.

Line2D class support creation using double parameters.