001 package fang;
002
003 import java.awt.Color;
004 import java.awt.Dimension;
005 import java.awt.Font;
006 import java.awt.Graphics;
007 import java.awt.Insets;
008 import java.awt.event.ComponentEvent;
009 import java.awt.event.ComponentListener;
010
011 import javax.swing.JButton;
012
013 /**This class represents a button which
014 * can animate the background and also
015 * resize the font with changes in the
016 * button size.
017 * @author Jam Jenkins
018 */
019 @SuppressWarnings("serial")
020 public class FunButton
021 extends JButton
022 implements ComponentListener
023 {
024 /**the previous width of the button*/
025 private int oldWidth = -1;
026
027 /**
028 * constructs a button with a given size and no text
029 * @param size
030 */
031 public FunButton(Dimension size)
032 {
033 this("", size);
034 }
035
036 /**
037 * constructs a button with a given size and text
038 * @param text the characters to appear on the button
039 * @param size the starting size of the button
040 */
041 public FunButton(String text, Dimension size)
042 {
043 super(text);
044 this.setBackground(Color.RED);
045 this.setMargin(new Insets(1, 1, 1, 1));
046 this.setOpaque(true);
047 FunPainter.setProperties(size, this);
048 this.addComponentListener(this);
049
050 }
051
052 /**
053 * uses the FunPainter to draw the background
054 * then uses the normal Button painting to
055 * draw everything else
056 * @param g the graphics used to draw
057 */
058 public void paintComponent(Graphics g)
059 {
060 if (oldWidth < 0)
061 {
062 oldWidth = getSize().width;
063 }
064 super.paintComponent(g);
065 setOpaque(false);
066 }
067
068 /**
069 * tracks changes in size in order to change
070 * the font size
071 * @param arg0 not used
072 */
073 public void componentResized(ComponentEvent arg0)
074 {
075 if (oldWidth < 0)
076 return ;
077 Font font = getFont();
078 double scaleX = getSize().width / (double)oldWidth;
079 oldWidth = getSize().width;
080 font = font.deriveFont((float)(scaleX * font.getSize2D()));
081 setFont(font);
082 }
083
084 /**
085 * does nothing
086 * @param arg0 ignored
087 */
088 public void componentMoved(ComponentEvent arg0)
089 {}
090
091 /**
092 * does nothing
093 * @param arg0 ignored
094 */
095 public void componentShown(ComponentEvent arg0)
096 {}
097
098 /**
099 * does nothing
100 * @param arg0 ignored
101 */
102 public void componentHidden(ComponentEvent arg0)
103 {}
104 }