package menu;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestMenu extends JFrame implements ActionListener,ItemListener{
MenuBar mb;
Menu m1;
Menu m2;
MenuItem mi1;
MenuItem mi2;
MenuItem mi3;
MenuItem mi4;
CheckboxMenuItem cbmi;//复选框菜单
static PopupMenu pm;//弹出式菜单
MenuItem pmi1,pmi2,pmi3;//弹出式菜单项
TextArea ta;
public TestMenu() {
mb = new MenuBar();
m1 = new Menu("颜色");
m2 = new Menu("窗口");
mi1 = new MenuItem("红色");
mi2 = new MenuItem("绿色");
mi3 = new MenuItem("蓝色");
mi4 = new MenuItem("关闭");
cbmi = new CheckboxMenuItem("斜体");
pm = new PopupMenu("弹出市菜单");
ta = new TextArea("弹出式菜单",10,30);
ta.setBounds(40,65,180,80);
this.add(ta);
mb.add(m1);
mb.add(m2);
m1.add(mi1);
m1.add(mi2);
m1.add(mi3);
m1.addSeparator();
m1.add(cbmi);
m2.add(mi4);
this.setMenuBar(mb);
pmi1 = new MenuItem("红色");
pmi2 = new MenuItem("绿色");
pmi3 = new MenuItem("蓝色");
pm.add(pmi1);pm.add(pmi2);pm.add(pmi3);
pmi1.addActionListener(this);
pmi2.addActionListener(this);
pmi3.addActionListener(this);
this.add(pm);
ta.addMouseListener(new MyMouseList());
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi4.addActionListener(this);
cbmi.addActionListener(this);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setBounds(300,80,260,170);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
MenuItem mi = (MenuItem)e.getSource();
String miLab = mi.getLabel();
if(miLab == "红色") ta.setForeground(Color.red);
if(miLab == "蓝色") ta.setForeground(Color.blue);
if(miLab == "绿色") ta.setForeground(Color.green);
if(miLab == "关闭") {System.exit(0);}
this.setTitle("设置文字颜色为【"+miLab+"】");
}
public void itemStateChanged(ItemEvent e) {//处理复选框菜单项的方法
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());
//(Component)mce.getSource()得到弹出式菜单这个对象
}
}
}
public static void main(String[] args) {
new TestMenu();
}
}
第一个问题:设置斜体没有效果。
第二个问题:右键弹出菜单设置颜色后,有弹出不出不希望的东西,怎么解决?