package edu.unc.sunsite.cafeaulait; import java.awt.*; public class StringBean extends Component { // properties private String text; public static void main(String[] args) { Frame f = new Frame("String Beans"); f.setLayout(new GridLayout(4, 1)); f.setSize(300, 400); f.setLocation(100, 100); // test the default constructor StringBean sb = new StringBean(); f.add(sb); sb = new StringBean("I am a bean!"); f.add(sb); Font fo = new Font("Helvetica", Font.BOLD, 24); sb = new StringBean("I am a bold green bean!", Color.green, fo); f.add(sb); sb = new StringBean("I am an italic red bean!", Color.red, "TimesRoman", Font.ITALIC, 18); f.add(sb); f.show(); } public StringBean() { this("Hello", Color.black, new Font("Helvetica", Font.PLAIN, 12)); } public StringBean(String text) { this(text, Color.black, new Font("Helvetica", Font.PLAIN, 12)); } public StringBean(String text, Color c) { this(text, c, new Font("Helvetica", Font.PLAIN, 12)); } public StringBean(String text, Color c, String fontName) { this(text, c, new Font(fontName, Font.PLAIN, 12)); } public StringBean(String text, Color c, String fontName, int fontSize) { this(text, c, new Font(fontName, Font.PLAIN, fontSize)); } public StringBean(String text, Color c, String fontName, int fontStyle, int fontSize) { this(text, c, new Font(fontName, fontStyle, fontSize)); } public StringBean(String text, Font f) { this(text, Color.black, f); } public StringBean(String text, Color c, Font f) { this.text = text; super.setFont(f); super.setForeground(c); } public String getText() { return text; } public void setText(String s) { text = s; } public void paint(Graphics g) { Font f = super.getFont(); FontMetrics fm = super.getFontMetrics(f); g.setFont(f); g.setColor(super.getBackground()); Rectangle r = super.getBounds(); g.fillRect(r.x, r.y, r.width, r.height); g.setColor(super.getForeground()); g.drawString(text, 5, fm.getMaxAscent()); } public Dimension getMinimumSize() { return getPreferredSize(); } public Dimension getPreferredSize() { FontMetrics fm = super.getFontMetrics(super.getFont()); return new Dimension(fm.stringWidth(text) + 10, fm.getMaxAscent() + fm.getMaxDescent()); } }