You can implement
getValueAtCoordinates
by reversing the centering and scaling calculations.
The method casts the relative x coordinate to a float
before
division to prevent rounding down to zero, and then uses the
round
class method in the Math
class to round the result
returned to the nearest long
, which is cast to the required
int
result:
import java.awt.*; import javax.swing.*; public class Meter extends JComponent implements MeterInterface { String title = "Title to be Supplied"; int minValue, maxValue, value; public Meter (int x, int y) { minValue = x; maxValue = y; value = (y + x) / 2; } public void setValue(int v) {value = v; repaint();} public void setTitle(String t) {title = t; repaint();} public int getValueAtCoordinates (int x, int y) { Dimension d = getSize(); int meterWidth = d.width * 3 / 4; int xOffset = (d.width - meterWidth) / 2; float fraction = (float)(x - xOffset) / meterWidth; return (int)Math.round(fraction * (maxValue - minValue) + minValue); } // Define paint as in Segment 733 public Dimension getMinimumSize() {return new Dimension(150, 150);} public Dimension getPreferredSize() {return new Dimension(150, 150);} }