Java 1.2 introduces a new GUI component library called swing. § swing includes javax.swing package and its subpackages. § swing has a platform independent implementation and an attribute set of artistic state. § although swing is independent of AWT, it is implemented according to the basic AWT class.
import java.awt.*;
import java.awt.event.*;
public class Javase_58 extends Frame implements ActionListener,ItemListener
{
static Javase_58 frm=new Javase_58 ();
static MenuBar mb=new MenuBar(); //创建MenuBar对象mb
static Menu m1=new Menu("颜色"); //创建Menu对象m1
static Menu m2=new Menu("窗口"); //创建Menu对象m2
static MenuItem mi1=new MenuItem("红色"); //创建MenuItem对象mi1
static MenuItem mi2=new MenuItem("绿色");
static MenuItem mi3=new MenuItem("蓝色");
static MenuItem mi4=new MenuItem("关闭");
static CheckboxMenuItem cbmi=new CheckboxMenuItem("斜体"); //复选框菜单项
static PopupMenu pm=new PopupMenu("弹出式菜单"); //创建弹出式菜单
static MenuItem Pop_m1,Pop_m2,Pop_m3; //弹出菜单项
static TextArea ta=new TextArea ("菜单程序设计",10,30);
public static void main(String[] args)
{
frm.setLayout(null); //取消页面设置
frm.setLocation(100,80);
frm.setSize(260,170);
frm.add(ta);
ta.setBounds(40,65,180,80);
mb.add(m1); //将m1加入到mb中
mb.add(m2);
m1.add(mi1); //将mi1加入到m1中
m1.add(mi2);
m1.add(mi3);
m1.addSeparator(); //加一分隔线
m1.add(cbmi); //添加带复选框的菜单项
m2.add(mi4); //将mi4加入到m2中
frm.setMenuBar(mb); //设置frm的菜单栏为mb
Pop_m1= new MenuItem("红色");
Pop_m2= new MenuItem("绿色");
Pop_m3= new MenuItem("蓝色");
pm.add(Pop_m1); //向弹出式菜单中添加菜单项
pm.add(Pop_m2);
pm.add(Pop_m3);
Pop_m1.addActionListener(frm); //设置frm为弹出菜单项的监听者
Pop_m2.addActionListener(frm);
Pop_m3.addActionListener(frm);
frm.add(pm); //将弹出式菜单附加在frm上
ta.addMouseListener (new MyMouseList()); //设置内部类为ta的监听者
mi1.addActionListener(frm); //设置frm为mi1的事件监听者
mi2.addActionListener(frm);
mi3.addActionListener(frm);
cbmi.addItemListener(frm); //设置frm为带复选框菜单项的监听者
mi4.addActionListener(frm);
frm.setVisible(true);
}
public void actionPerformed(ActionEvent e) //事件处理的程序代码
{
MenuItem mi=(MenuItem)e.getSource(); //取得引发事件的对象
String miLab=mi.getLabel(); //取得菜单项的文字标题
if(miLab=="红色")
ta.setForeground(Color.red);
else if(miLab=="绿色")
ta.setForeground (Color.green);
else if(miLab=="蓝色")
ta.setForeground (Color.blue);
else if(mi==mi4)
frm.dispose(); //关闭窗口,释放资源
frm.setTitle("设置文字颜色为【"+miLab+"】");
}
public void itemStateChanged(ItemEvent ie) //处理复选框菜单项的方法
{
boolean yn= cbmi.getState();
if (yn) ta.setFont(new Font("楷体_GB2312",Font.ITALIC,15));
else ta.setFont(new Font("宋体",Font.PLAIN,15));
}
static class MyMouseList extends MouseAdapter //处理鼠标事件的类
{
public void mouseReleased(MouseEvent mce) //释放鼠标时触发的事件
{
if (mce.isPopupTrigger()) //判断鼠标事件是否是由弹出菜单引发
pm.show((Component)mce.getSource(),mce.getX(),mce.getY());
}
}
}