JAVA popupMenu弹出菜单了,怎样实现点击项产生事件
展开全部
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;
/**
* 右键弹出菜单测试类
*/
public class PopupMenuTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1282599344832870566L;
private JTextArea txtArea;
private JMenuItem menuItem;
private JPopupMenu popMenu;
public PopupMenuTest() {
setSize(200, 200);
setLayout(new BorderLayout());
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout());
txtArea = new JTextArea();
panel.add(txtArea, BorderLayout.CENTER);
txtArea.setText("右键清除内容");
popMenu = new JPopupMenu();
menuItem = new JMenuItem("清除");
menuItem.addActionListener(actionListener);
popMenu.add(menuItem);
txtArea.addMouseListener(mouseAdapter);
}
/**
* 文本区鼠标监听事件,右键弹出菜单。
*/
private MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if (e.getButton() == MouseEvent.BUTTON3) {
popMenu.show(txtArea, e.getX(), e.getY());
}
}
};
/**
* 弹出菜单响应事件
*/
private ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == menuItem) {
txtArea.setText("");
}
}
};
public static void main(String[] args) {
PopupMenuTest popTest = new PopupMenuTest();
popTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
popTest.setVisible(true);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询