小玩JButton _告辞生硬的按钮
小玩JButton _告别生硬的按钮
一、运行后,窗体上显示两个自制按钮
二、鼠标放上按钮后效果:
三、制作步骤:
(1)预先做好的按钮的图片(见附件按钮图标)
(2)调用JButton的父类AbstractButton类的三个方法:
setIcon(Icon defaultIcon)
设置按钮的默认图标。
setPressedIcon(Icon pressedIcon) 设置按钮的按下图标。
setSelectedIcon(Icon selectedIcon) 设置按钮的选择图标。
(3)AbstractButton的子类:
JButton、JCheckBox、JRadioButton、 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) {} } }