小玩JButton _告别生硬的按钮

一、运行后,窗体上显示两个自制按钮


 


二、鼠标放上按钮后效果:

 

三、制作步骤:

(1)预先做好的按钮的图片(见附件按钮图标)

(2)调用JButton的父类AbstractButton类的三个方法:

    setIcon(Icon defaultIcon)                    设置按钮的默认图标。
    setPressedIcon(Icon pressedIcon)   设置按钮的按下图标。
    setSelectedIcon(Icon selectedIcon) 设置按钮的选择图标。

(3)AbstractButton的子类:

   JButtonJCheckBoxJRadioButton JMenuItem

所以以上四个组件均可用同样的方法进行美化。

 


四、具体的代码实现:

 

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;

public class FancyButton extends JButton {

	private ButtonAction ba;
	/**
	 * 构造器
	 * @param icon:按钮默认的图标
	 * @param pressed:鼠标点击按钮显示的图标
	 * @param rollover:鼠标放在按钮上显示的图标
	 */
  public FancyButton(Icon icon, Icon pressed, Icon rollover) {
    setFocusPainted(false);
    //设置翻转效果
    setRolloverEnabled(true);
    //鼠标放在按钮上替换显示的图标
    setRolloverIcon(rollover);
    //鼠标点击按钮替换显示的图标
    setPressedIcon(pressed);
    //将按钮设置为无边框
    setBorderPainted(false);
    //设置按钮为透明,无填充效果,只显示替换的图标
    setContentAreaFilled(false);
    ba=new ButtonAction(icon);
    this.setAction(ba);
  }

  public static void main(String[] args) {

    FancyButton b1 = new FancyButton(
      new ImageIcon("images/2.png"),
      new ImageIcon("images/8.png"),
      new ImageIcon("images/9.png"));
    FancyButton b2 = new FancyButton(
      new ImageIcon("images/14.png"),
      new ImageIcon("images/15.png"),
      new ImageIcon("images/16.png"));
    JFrame f = new JFrame( );
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container c = f.getContentPane( );
    c.setLayout(new FlowLayout( ));
    c.add(b1);
    c.add(b2);
    //调整此窗口的大小,以适合其子组件的首选大小和布局。
    f.pack( );
    f.setVisible(true);
  }

  public class ButtonAction extends AbstractAction{
		public ButtonAction(Icon icon){
		    putValue(SHORT_DESCRIPTION, "鼠标放上按钮,图标改变了哦!");
		    putValue(SMALL_ICON,icon);
		}
		@Override
		public void actionPerformed(ActionEvent e) {}
	}


}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值