扩展按钮

    技术2022-05-11  67

    import java.awt.*; import java.awt.geom.*; import javax.swing.*; import java.io.*; public class custom_button extends JButton {         Image img;     public Color back;     ImageIcon icon = new ImageIcon ();     public custom_button ()     {         super ();         Dimension size = getPreferredSize ();         size.width = size.height = Math.max (size.width, size.height);         setPreferredSize (size);         //这个调用使JButton不画背景,而允许画一个圆的背景。         setContentAreaFilled (false);     }             public custom_button (String label)     {         super (label);         // 这些声明把按钮扩展为一个圆而不是一个椭圆。         Dimension size = getPreferredSize ();         size.width = size.height = Math.max (size.width, size.height);         setPreferredSize (size);                 //这个调用使JButton不画背景,而允许我们画一个圆的背景。         setContentAreaFilled (false);     }         // 画圆的背景和标签     protected void paintComponent (Graphics g)     {         if (getModel ().isArmed ())         {                         // 可以选一个高亮的颜色作为圆形按钮类的属性             g.setColor (back);         }         else         {             g.setColor (back);         }         g.fillRect (0, 0, getSize ().width, getSize ().height);                 //这个调用会画一个标签和焦点矩形。         super.paintComponent (g);     }             public void setImageIcon (Image img)     {         this.img = img;     }         // 用简单的弧画按钮的边界。     protected void paintBorder (Graphics g)     {         //g.setColor(back);         //g.drawRect(-1, -1, getSize().width + 1 , getSize().height + 1);     }             // 侦测点击事件     Shape shape;     public boolean contains (int x, int y)     {         // 如果按钮改变大小,产生一个新的形状对象。         if (shape == null ||                 !shape.getBounds ().equals (getBounds ()))         {             shape = new Ellipse2D.Float (0, 0, getWidth (), getHeight ());         }         return shape.contains (x, y);     }         //下面都是测试代码     public void init ()     {        icon = new ImageIcon (getClass ().getResource ("clear1.jpg"));        this.setIcon((Icon) icon) ;        icon = new ImageIcon (getClass ().getResource ("clear2.jpg"));        this.setRolloverIcon((Icon) icon);        this.setPressedIcon ((Icon) icon);         //return icon;     }     public static void main (String args[])     {         JFrame frame = new JFrame ("test");         frame.setLayout(null);         custom_button btn = new custom_button ();         btn.init();        btn.back = frame.getContentPane ().getBackground () ;         btn.setToolTipText ("test");         btn.setBounds (100,100 ,62,21) ;         frame.add (btn);         frame.setSize (300,300);         frame.setVisible (true);         frame.setDefaultCloseOperation (3);     }     }  

    最新回复(0)