import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class notepad { /**
* @param args
*/
public static void main(String[] args) {
new notePadWindow("记事本"); }}
class notePadWindow extends JFrame implements ActionListener
{
JMenuBar menubar;
JMenu menu;
JMenuItem itemCopy,itemCut,itemPaste;
JTextArea text;
JPopupMenu pmenu;
notePadWindow(String title)
{
setTitle(title);
pmenu=new JPopupMenu();
text=new JTextArea();
add(text);
text.setLineWrap(true);
menubar=new JMenuBar();
menu=new JMenu("编辑");
itemCopy=new JMenuItem("复制");
itemCut=new JMenuItem("剪切");
itemPaste=new JMenuItem("粘贴");
itemCopy.addActionListener(this);
itemCut.addActionListener(this);
itemPaste.addActionListener(this);
menu.add(itemCopy);
menu.add(itemCut);
menu.add(itemPaste);
//pmenu.add(itemCopy); //此处如果不注释掉 则"编辑"菜单中的"复制","粘贴"
//"剪切"就不会显示
//pmenu.add(itemCut);
//pmenu.add(itemPaste);
menubar.add(menu);
setJMenuBar(menubar);
setBounds(100,100,400,600);
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
validate();
text.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
if(e.getModifiers()==InputEvent.BUTTON3_MASK)
pmenu.show(text,e.getX(),e.getY());
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==itemCopy)
text.copy();
else if(e.getSource()==itemCut)
text.cut();
else if(e.getSource()==itemPaste)
text.paste();
}
}能不能用将同一个对象,比如说这里的itemCopy itemCut itemPaste同时添加到“编辑”菜单和右键菜单中
,然后再对菜单各项添加侦听器,我不想再创建 itemCopy1,itemCut1,itemPaste1之类的对象去实现相同的功能...
现在有“编辑”菜单就没有右键快捷菜单,有右键快捷菜单就没有“编辑”菜单...
一个MenuItem等控件只能加入到一个,也是最后加入的那个容器中