JavaSE系列代码49:选项事件类的应用

The main purpose of Java generics is to build data structures with type safety, such as linked lists, hash tables and other data structures. The most important advantage is that when using the data structures built by these generic classes, there is no need to cast, that is, there is no need to run-time type checking. SDK 1.5 is a compiler that supports generics. It advances runtime type checking to compile time, making code safer.

import java.awt.*; 
import java.awt.event.*; 
public class Javase_49 extends Frame implements ItemListener
{
  static app13_4 frm=new app13_4();
  static Checkbox chk1=new Checkbox("租体");
  static Checkbox chk2=new Checkbox("斜体");
  static Checkbox chk_g1=new Checkbox("红色");
  static Checkbox chk_g2=new Checkbox("蓝色");
  static TextArea ta=new TextArea ("选项事件类ItemEvent的使用方法",8,30);
  public static void main(String[] args)
  {
    CheckboxGroup grp=new CheckboxGroup();  //创建一个单按钮组对象
     frm.setTitle("选项事件处理");
    frm.setLocation(200,150);
    frm.setSize(250,220);
    frm.setLayout(new FlowLayout(FlowLayout.LEFT)); 
    chk_g1.setCheckboxGroup(grp);   //将chk_g1设置为单选按钮
    chk_g2.setCheckboxGroup(grp);
    chk1. addItemListener(frm);      //设置frm为chk1的监听者
    chk2. addItemListener(frm);      //设置frm为chk2的监听者
    chk_g1.addItemListener(frm);    //设置frm为chk_g1的监听者
    chk_g2.addItemListener(frm);    //设置frm为chk_g2的监听者
    frm.add(chk1);
    frm.add(chk2);
    frm.add(chk_g1);
    frm.add(chk_g2);
    frm.add(ta);
    frm.setVisible(true);
  }
  //ItemEvent事件发生时的处理操作
  public void itemStateChanged(ItemEvent e)
  {
    Checkbox chk=(Checkbox)e.getSource(); //获得事件源
    Font font1=ta.getFont();
    int style1=font1.getStyle();
    if(chk==chk_g1) ta.setForeground(Color.RED);
    else if(chk==chk_g2) ta.setForeground(Color. BLUE);
    else if((chk==chk1)||( chk==chk2))
    {
      if(chk==chk1) style1=style1^1;   //按位异或运算^
      if(chk==chk2) style1=style1^2;
      ta.setFont(new Font(font1.getName(),style1,font1.getSize()));
      ta.append("\nstyle="+style1+"  "+e.getItem()+"  " +chk.getState());
    }
  }
}
发布了52 篇原创文章 · 获赞 162 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/blog_programb/article/details/105394992
今日推荐