package awt;

import java.awt.*;

This class is a lightweight version of java.awt.Label. Moreover, its preferred size changes when the label text is changed, unlike java.awt.Label.
public class Label extends Component { public static final int LEFT=java.awt.Label.LEFT; public static final int CENTER=java.awt.Label.CENTER; public static final int RIGHT=java.awt.Label.RIGHT; private String text; private int alignment; private String mintext; public Label(String txt) { text = txt; } public Label(String txt,int align) { text = txt; alignment = align; } // public void addNotify() public int getAlignment() { return alignment; } public void setAlignment(int align) { alignment = align; repaint(); } public String getText() { return text; } public void setText(String txt) { text = txt; repaint(); } protected String paramString() { String str = "?"; switch (alignment) { case LEFT: str = "left"; break; case CENTER: str = "center"; break; case RIGHT: str = "right"; break; } return super.paramString()+",align="+str+",text="+text; }
Own method. The Label should try to be at least as wide as the given string.
public void setMinText(String str) { mintext = str; } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getPreferredSize() { FontMetrics fm; try { fm = getFontMetrics(getFont()); } catch (Exception e) { fm = null; } if (fm == null) return new Dimension(30,10); int width1 = text==null ? 0 : fm.stringWidth(text); int width2 = mintext==null ? 0 : fm.stringWidth(mintext); return new Dimension(width1>width2 ? width1 : width2,fm.getHeight()); } public void paint(Graphics g) { paint(g,true); } protected void paint(Graphics g,boolean erasebg) { Dimension siz = getSize(); if (erasebg) { // Lightweight components need to erase background themselves g.setColor(getBackground()); g.fillRect(0,0,siz.width,siz.height); } if (text == null) return; g.setColor(getForeground()); FontMetrics fm = g.getFontMetrics(); int ypos = (siz.height-fm.getHeight())/2+fm.getAscent(); switch (alignment) { default: case CENTER: g.drawString(text,(siz.width-fm.stringWidth(text))/2,ypos); break; case LEFT: g.drawString(text,0,ypos); break; case RIGHT: g.drawString(text,siz.width-fm.stringWidth(text),ypos); break; } // very strange bug in jdk1.2 g.setColor(getBackground()); g.drawLine(0,0,0,0); } public void update(Graphics g) { paint(g,true); } public void setFont(Font f) { super.setFont(f); repaint(); } }