1 | // Copyright 2004-2007 Jean-Francois Poilpret |
2 | // |
3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | // you may not use this file except in compliance with the License. |
5 | // You may obtain a copy of the License at |
6 | // |
7 | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | // |
9 | // Unless required by applicable law or agreed to in writing, software |
10 | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | // See the License for the specific language governing permissions and |
13 | // limitations under the License. |
14 | |
15 | package net.sourceforge.hivegui.component; |
16 | |
17 | import java.awt.AWTError; |
18 | import java.awt.Component; |
19 | import java.awt.Container; |
20 | import java.awt.Dimension; |
21 | import java.awt.Insets; |
22 | import java.awt.LayoutManager; |
23 | |
24 | /** |
25 | * Simple LayoutManager that allows to center a single Component inside a |
26 | * Container, based on its preferred size. |
27 | * |
28 | * @author jean-Francois Poilpret |
29 | */ |
30 | public class CenterLayout implements LayoutManager |
31 | { |
32 | public void addLayoutComponent(String name, Component comp) |
33 | { |
34 | } |
35 | |
36 | public void removeLayoutComponent(Component comp) |
37 | { |
38 | } |
39 | |
40 | public Dimension preferredLayoutSize(Container target) |
41 | { |
42 | Component content = checkTarget(target); |
43 | return content.getPreferredSize(); |
44 | } |
45 | |
46 | public Dimension minimumLayoutSize(Container target) |
47 | { |
48 | Component content = checkTarget(target); |
49 | return content.getMinimumSize(); |
50 | } |
51 | |
52 | public void layoutContainer(Container target) |
53 | { |
54 | Component content = checkTarget(target); |
55 | |
56 | // Find the available size of the container |
57 | Dimension alloc = target.getSize(); |
58 | Insets in = target.getInsets(); |
59 | alloc.width -= in.left + in.right; |
60 | alloc.height -= in.top + in.bottom; |
61 | |
62 | int width = content.getPreferredSize().width; |
63 | int height = content.getPreferredSize().height; |
64 | |
65 | int x = (alloc.width - width) / 2; |
66 | if (x < 0) |
67 | { |
68 | x = 0; |
69 | width = alloc.width; |
70 | } |
71 | int y = (alloc.height - height) / 2; |
72 | if (y < 0) |
73 | { |
74 | y = 0; |
75 | height = alloc.height; |
76 | } |
77 | |
78 | content.setBounds(x + in.left, y + in.top, width, height); |
79 | } |
80 | |
81 | private Component checkTarget(Container target) |
82 | { |
83 | if (target.getComponentCount() != 1) |
84 | { |
85 | throw new AWTError("CenterLayout must have exactly one component"); |
86 | } |
87 | return target.getComponent(0); |
88 | } |
89 | } |