1

Is it contraindicated to use several presetted dimension objects to set the preferred size of non resizable components on the screen. E.g.: two textfields both should be 80x20 px so:

Dimension d = new Dimension(80, 20);
tf1.setPreferredSize(d);
tf2.setPreferredSize(d);
zeller
  • 4,904
  • 2
  • 22
  • 40
  • 3
    The real question is: should you really call `setPreferreedSize()` on a `JTextField` (or any Swing `JComponent`)? The answer is NO, it is a very bad practice. – jfpoilpret Sep 15 '11 at 11:57
  • 1
    "In medicine, a contraindication is a condition or factor that serves as a reason to withhold a certain medical treatment." – Charles Goodwin Sep 15 '11 at 12:05

1 Answers1

4

Yes, it is "safe". Quote from Java Performance Tuning:

[...] This same Dimension object can be reused for multiple components. [...]

Depends on what you want though. Note that the implementation in Component does not copy the content of the argument, but stores the reference:

public void setPreferredSize(Dimension preferredSize) {
    ...
    this.prefSize = preferredSize;
    ...
}

so changing d will affect the dimension object stored in both tf1 and tf2.

(What I'm saying is that the code below may not do what you would expect.)

Dimension d = new Dimension(80, 20);
tf1.setPreferredSize(d);

d.width += 1;               // <-- will affect also tf1.
tf2.setPreferredSize(d);
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 2
    But neither `tf1` *nor* `tf2` will be *notified* when you change `d`, so they can only find out about it "by chance". That's why I think making things like `Dimension` mutable is a bad idea. – Joachim Sauer Sep 15 '11 at 11:44
  • 1
    @Joachim, actually Sun making `Dimension`, `Point`, `Rectangle`... mutable was a bad design decision initially, hence now it's up to developers to care about this fact, and code defensively against mutability of instances of such classes. – jfpoilpret Sep 15 '11 at 12:00
  • I don't think the question primarily was primarily about "what happens if I modify the dimension object". The question was more on whether or not it is considered safe. My mentioning of "changing `d`" was to clarify that he can't do `tf1.setPrefSize(d); d.width += 5; tf2.setPrefSize(d);`. – aioobe Sep 15 '11 at 12:07