【Java开源代码栏目提醒】:网学会员在Java开源代码频道为大家收集整理了ButtonIcon.java提供大家参考,希望对大家有所帮助!
package Chapter13;
//文件:程序13.2 ButtonIcon.java 描述:JButton演示
//导入需要使用的包和类
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class ButtonIcon extends JPanel implements ActionListener {
public static void main(String[] args) {
JFrame jf = new JFrame(); // 创建,并初始化窗口对象jf
ButtonIcon bi = new ButtonIcon(); // 创建,并初始化图标对象bi
jf.getContentPane().add(bi); // 获取面板容器,并添加按钮
jf.setSize(400, 130); // 设置窗口大小
jf.setVisible(true); // 显示窗口
jf.addWindowListener(new WindowAdapter() {
// 匿名类用于注册监听器
public void windowClosing(WindowEvent e) {
System.exit(0);
} // 程序退出
});
}
// 声明ButtonIcon类构造方法
public ButtonIcon() {
super(); // 调用父类构造方法
button = new JButton[3]; // 初始化JButton数组
imageIcon = new ImageIcon[3]; // 初始化ImageIcon数组
// 保存三个图标
imageIcon[0] = new ImageIcon("images\\first.gif"); // 初始化图标imageIcon[0]
imageIcon[1] = new ImageIcon("images\\second.gif"); // 初始化图标imageIcon[1]
imageIcon[2] = new ImageIcon("images\\third.gif"); // 初始化图标imageIcon[2]
button[0] = new JButton(imageIcon[0]); // 初始化button[0]
button[1] = new JButton(imageIcon[1]); // 初始化button[1]
button[2] = new JButton(imageIcon[2]); // 初始化button[2]
add(button[0]); // 添加按钮button[0]
add(button[1]); // 添加按钮button[1]
add(button[2]); // 添加按钮button[2]
button[0].addActionListener(this); // 为按钮button[0]添加监听器ActionListener
button[1].addActionListener(this); // 为按钮button[1]添加监听器ActionListener
button[2].addActionListener(this); // 为按钮button[2]添加监听器ActionListener
}
public void actionPerformed(ActionEvent e) {
ImageIcon imageIconc; // 创建ImageIcon对象
if ((JButton) e.getSource() == button[0]) // 判断事件源是否是button[0]
{
for (int i = 0; i < 3; i++)
button[i].setIcon(imageIcon[(i + 1) % 3]); // 为button[i]设置图标
// 更换图标
imageIconc = imageIcon[0];
imageIcon[0] = imageIcon[1];
imageIcon[1] = imageIcon[2];
imageIcon[2] = imageIconc;
imageIconc = null; // 设置imageIconc为null
} else if ((JButton) e.getSource() == button[2]) // 判断事件源是否是button[2]
{
for (int i = 2; i >= 0; i--)
button[i].setIcon(imageIcon[(i - 1 + 3) % 3]); // 为button[i]设置图标
// 更换图标
imageIconc = imageIcon[2]; // 将imageIcon[2]引用指向imageIconc
imageIcon[2] = imageIcon[1]; // 将imageIcon[1]引用指向imageIcon[2]
imageIcon[1] = imageIcon[0]; // 将imageIcon[0]引用指向imageIcon[1]
imageIcon[0] = imageIconc; // 将imageIconc引用指向imageIcon[0]
imageIconc = null; // 设置imageIconc为null
}
}
JButton button[]; // 声明JButton类型数组button
ImageIcon imageIcon[]; // 声明ImageIcon类型数组imageIcon
}
上一篇:
ButtonHandler.java
下一篇:
法律专业开题报告范文