程序示例:
package MyJava.Base;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JButtonFrame extends JFrame
{
private JButton jbutton1;
private JButton jbutton2;
private JButton jbutton3;
private JButton jbutton4;
private JButton jbutton5;
public JButtonFrame(String title)
{
super(title);
setSize(400,500);
//获得容器
Container container=this.getContentPane();
//设置布局为6行一列
container.setLayout(new GridLayout(5,1));
//创建空的按钮
jbutton1=new JButton();
container.add(jbutton1);
//创建带有Icon的JButton
Icon pic=new ImageIcon("E://Java//JCreator2.5//picture//game.gif");
jbutton2=new JButton(pic);
container.add(jbutton2);
//创建含有文字的JButton
jbutton3=new JButton("I Love You");
container.add(jbutton3);
//创建含有文字和Icon的JButton
jbutton4=new JButton("I Love You",pic);
container.add(jbutton4);
jbutton5=new JButton();
//开始时的Icon
Icon general=new ImageIcon("E://Java//JCreator2.5//picture//general.gif");
//按钮按下去的时候的Icon
Icon press=new ImageIcon("E://Java//JCreator2.5//picture//nake.gif");
//鼠标在按钮范围里时的Icon
Icon roller=new ImageIcon("E://Java//JCreator2.5//picture//cloth.gif");
jbutton5.setIcon(general);
jbutton5.setPressedIcon(press);
jbutton5.setRolloverIcon(roller);
container.add(jbutton5);
this.getRootPane().setDefaultButton(jbutton4); //设置默认按钮
}
}
public class JButtonDemo
{
public static void main(String[] args) throws Exception
{
JButtonFrame frame=new JButtonFrame("JButtonDemo");
// frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
程序运行结果:
开始时的Icon;
鼠标在jbutton5的范围时的Icon;
鼠标按下jbutton5时的Icon