KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jac > aspects > gui > swing > SwingUtils


1 /*
2   Copyright (C) 2004 Laurent Martelli <laurent@aopsys.com>
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU Lesser General Public License as
6   published by the Free Software Foundation; either version 2 of the
7   License, or (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12   GNU Lesser General Public License for more details.
13
14   You should have received a copy of the GNU Lesser General Public
15   License along with this program; if not, write to the Free Software
16   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17   USA */

18
19 package org.objectweb.jac.aspects.gui.swing;
20
21 import java.awt.Component JavaDoc;
22 import java.awt.Dimension JavaDoc;
23 import java.awt.FontMetrics JavaDoc;
24 import javax.swing.JComponent JavaDoc;
25 import org.objectweb.jac.aspects.gui.Length;
26 import org.objectweb.jac.aspects.gui.Unit;
27
28 public class SwingUtils {
29     public static int getPixelLength(Length l, Component JavaDoc c) {
30         FontMetrics JavaDoc metrics = c.getFontMetrics(c.getFont());
31         if (l.unit == Unit.EM) {
32             return (int)(l.value * metrics.getHeight());
33         } else if (l.unit == Unit.EX) {
34             return (int)(l.value * metrics.charWidth('x'));
35         } else if (l.unit == Unit.PX) {
36             return (int)l.value;
37         } else {
38             throw new RuntimeException JavaDoc("Unhandled unit: "+l.unit);
39         }
40     }
41
42     public static void setSize(JComponent JavaDoc c, Length width, Length height) {
43         if (width!=null || height!=null) {
44             Dimension JavaDoc dim = c.getPreferredSize();
45             if (width!=null)
46                 dim.width = SwingUtils.getPixelLength(width,c);
47             if (height!=null)
48                 dim.height = SwingUtils.getPixelLength(height,c);
49             c.setPreferredSize(dim);
50         }
51     }
52
53     public static void setColumns(javax.swing.JTextField JavaDoc textField, Length width) {
54         if (width != null && width.unit == Unit.EX)
55             textField.setColumns((int)width.value);
56     }
57 }
58
Popular Tags