标签:class blog code java http ext
JCheckBox和JRadioButton的事件处理监听接口是一样的,都是使用ItemListener接口。
package com.beyole.util; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; class MyItemListener implements ItemListener { private String right = "f:" + File.separator + "2.png"; private String wrong = "f:" + File.separator + "3.png"; public void itemStateChanged(ItemEvent e) { JCheckBox jcb = (JCheckBox) e.getItem();// 将得到的事件强制转化为JCheckBox类 if (jcb.isSelected()) {// 判断是否被选择 jcb.setIcon(new ImageIcon(right));// 修改图片 } else { jcb.setIcon(new ImageIcon(wrong));// 修改图片 } } } class MyCheckBox1 { private String wrong = "f:" + File.separator + "3.png";// 定义图片路径 private JFrame frame = new JFrame("Beyole");// 定义窗体 private Container container = frame.getContentPane();// 得到窗体容器 private JCheckBox jcb1 = new JCheckBox("主站", new ImageIcon(wrong)); private JCheckBox jcb2 = new JCheckBox("论坛", new ImageIcon(wrong)); private JCheckBox jcb3 = new JCheckBox("博客", new ImageIcon(wrong)); private JPanel panel = new JPanel();// 定义一个面板 public MyCheckBox1() { panel.setBorder(BorderFactory.createTitledBorder("请选择你最喜欢的网站"));// 定义一个边框的显示条 panel.setLayout(new GridLayout(1, 3));// 定义排版 1行3列 panel.add(this.jcb1);// 加入组件 panel.add(this.jcb2);// 加入组件 panel.add(this.jcb3);// 加入组件 jcb1.addItemListener(new MyItemListener());// 加入监听 jcb2.addItemListener(new MyItemListener());// 加入监听 jcb3.addItemListener(new MyItemListener());// 加入监听 container.add(panel);// 加入面板 this.frame.setSize(330, 100);// 定义窗体大小 this.frame.setVisible(true);// 显示窗体 this.frame.addWindowListener(new WindowAdapter() {// 加入事件监听 public void windowClosing(WindowEvent arg0)// 复写窗口关闭方法 { System.exit(1);// 系统退出 } }); } } public class JCheckBoxDemo02 { public static void main(String[] args) { new MyCheckBox1(); } }
程序截图:
Java Swing界面编程(29)---JCheckBox事件处理,布布扣,bubuko.com
Java Swing界面编程(29)---JCheckBox事件处理
标签:class blog code java http ext
原文地址:http://blog.csdn.net/xuejiawei123/article/details/30779757