import java.awt.*; import java.awt.font.*; import java.awt.geom.*; import java.awt.image.*; public class TransparentLabel extends Component { protected String text; protected transient BufferedImage image; protected transient Graphics2D g2d; protected int width; protected int height; public void createLabel(String text, Color color){ this.text = text; TextLayout textLayout = new TextLayout(text, new Font("Serif", Font.BOLD, 12), new FontRenderContext(null, false, false)); Rectangle2D size = textLayout.getBounds(); width = (int)size.getWidth() + 6; height = (int)size.getHeight() + 2; setSize(width, height); image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); g2d = (Graphics2D)image.getGraphics(); g2d.setBackground(new Color(255, 255, 255, 0)); g2d.clearRect(0, 0, width, height); g2d.setColor(color); g2d.drawString(text, 0, 12); } public TransparentLabel(String text, Color color){ createLabel(text, color); } public TransparentLabel(String text){ createLabel(text, super.getForeground()); } public Dimension getPreferredSize(){ return getMinimumSize(); } public Dimension getMinimumSize(){ return new Dimension(width, height); } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ g.drawImage(image, 0, 0, width, height, this); } }