Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd also suggest some kind of interface/subclass solution for encapsulating the different layout calculations for different components. I also would add some registration mechanism in order to be flexible for future additions (if you want to implement another separate behaviour for new component types)</p> <pre><code>public interface PositionCalculator { Dimension calculatePositionForComponent(MyLayoutManager manager, Component component); } class JLabelCalculator implements PositionCalculator { public Dimension calculatePositionForComponent(MyLayoutManager manager, Component component) { // ... } } class JRadioButtonPosCalculator impements PositionCalculator { public Dimension calculatePositionForComponent(MyLayoutManager manager, Component component) { // ... } } // More classes ... class MyLayoutManager extends LayoutManager { private static HashMap&lt;Class, PositionCalculator&gt; calculators = new HashMap&lt;Class, PositionCalculator&gt;(); public static registerPositionCalculator(Class c, PositionCalculator p) { calculators.put(c, p); } private static PositionCalculator defaultCalculator = new DefaultPositionCalculator(); // Not shown here ... // ... private Dimension calculatePositionForComponent(Component c) { PositionCalculator calc = calculators.get(c.getClass()); if (calc == null) calc = defaultCalculator; return calc.calculatePositionForComponent(this, c); } } </code></pre> <p>Now, you can register individual PositionCalculators for all of your components by putting</p> <pre><code>MyLayoutManager.registerPositionCalculator(JLabel.class, new JLabelCalculator()); MyLayoutManager.registerPositionCalculator(JRadioButton.class, new JRadioButtonCalculator()); // ... </code></pre> <p>Of course, this solution might suffer from the following drawbacks:</p> <ul> <li>It's probably slower than the original one.</li> <li>It doesn't work with inherited classes: if you have a subclass from JLabel, you must register it separately. The solution could be adapted to this, but this would be at the cost of another performance loss...</li> </ul> <p>On the other hand, the solution is pretty well extensible: You can define different layout behaviour without touching your MyLayoutManager class.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload