HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

"The Argument for Custom Component UIs"
Vol. 2, Issue 11, p. 48


Listing 1. 
A simple custom component named ClickableLabel. All custom UI components in 1.0 
are derived from Canvas, Panel, Frame or Dialog (1.1 allows you to derived from 
Component, Container and  Window also). 

public class ClickableLabel extends Canvas { 
  protected String m_strLabel; 
  protected int m_hpad = 2; 
  protected boolean m_fMouseDown; 
  protected boolean m_fMouseIn; 

  public ClickableLabel(String strLabel) { 

  public void setLabel(String strLabel) { 
    m_strLabel = new String(strLabel); 

  public String getLabel() { 
    return new String(m_strLabel); 

  public void paint(Graphics g) { 
    // ensure foreground color and preferred 
    // font are selected into the Graphics 

    FontMetrics fm = g.getFontMetrics(getFont()); 
    int h = fm.getHeight(); 
    int ch = size().height; 
    int texttop = ch/2  h/2; 
    int y = texttop + fm.getAscent(); 
    g.drawString(m_strLabel, m_hpad, y); 

  public Dimension preferredSize() { 
    Graphics g = getGraphics(); 
    FontMetrics fm = g.getFontMetrics(getFont()); 

    return new Dimension(fm.stringWidth(m_strLabel) + 
        2 * m_hpad, fm.getHeight()); 

  public Dimension minimumSize() { 
    return preferredSize(); 

  // A mouse click event causes an ACTION_EVENT to be fired 
  // by this ClickableLabel 
  public boolean mouseEnter(Event evt) { 
    m_fMouseIn = true; 

  public boolean mouseExit(Event evt) { 
    m_fMouseIn = false; 

  public boolean mouseUp(Event evt) { 
    if(m_fMouseIn && m_fMouseDown) { 
      Event evtAction = new Event(this, 
    m_fMouseDown = false; 


All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.