0

I would like to set a rectangle position relative to another component, but offsetted. I tried the following:

rndRect.setLocation(StartButt.getLocation().translate(buttW, 2));

but translate returns void, so it is not accepted as a parameter (requires a Point).

Is there a way to do it on the same statement without creating an auxiliary variable?

Nothing crucial, just curiosity.

Stef
  • 45
  • 8

1 Answers1

0

No. If translate takes a mutable variable which is changed and not returned then you will need to declare a variable to pass to translate and then subsequently pass it to setLocation.

Alternatively you could write your own method that takes a location and creates and returns a point:

private Point translate(Location location, Point origin, int distance) {
    Point result = (Point)origin.clone();
    location.translate(result, distance);
    return result;
}

rndRect.setLocation(translate(StartButt.getLocation(), buttW, 2));

As a matter of interest, opinions vary (a lot) over whether it's a good idea to have interim variables to hold values temporarily or, alternatively, to create fewer more complex statements that avoid interim variables. Personally I find well named interim variables (and short simple methods) make reading code much easier as you have less to hold in your head as you read each statement. The code tends to reads more like a story and less like a puzzle. In my experience, as coders get better through their careers they create more and simpler classes, methods, statement and variables to solve each problem.

sprinter
  • 27,148
  • 6
  • 47
  • 78
  • I agree on splitting the code to make it more understandable, in this case though, it was pretty clear that I just wanted the same point, offsetted. – Stef Dec 18 '19 at 08:31
  • Sadly in Java you can't overload methods with the same parameters but different return types, otherwise there could be a method that returns the same object after altering it, like you wrote. Thank you for confirming that! – Stef Dec 18 '19 at 08:33