Java面板
import java.awt.*;import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
public class PopupMenuDemo extends MouseAdapter implements ActionListener {
JFrame frame = new JFrame("Popup Menu Demo");
JPopupMenu popup = new JPopupMenu();
JTextField tf = new JTextField();
JLabel label = new JLabel("点击右键弹出菜单。");
public void actionPerformed(ActionEvent e) {
tf.setText(e.getActionCommand());
if(e.getActionCommand() == "EXIT") {
System.exit(0);
}
}
public static void main(String[] args) {
PopupMenuDemo popupMenuDemo = new PopupMenuDemo();
popupMenuDemo.go();
}
public void go() {
JMenuItem menuItem = new JMenuItem("新建");
menuItem.addActionListener(this);
popup.add(menuItem);
menuItem = new JMenuItem("打开");
menuItem.addActionListener(this);
popup.add(menuItem);
menuItem = new JMenuItem("保存");
menuItem.addActionListener(this);
popup.add(menuItem);
popup.addSeparator();
menuItem = new JMenuItem("退出");
menuItem.addActionListener(this);
popup.add(menuItem);
label.addMouseListener(this);
tf.setEditable(false);
Container cp = frame.getContentPane();
cp.add(label,BorderLayout.CENTER);
cp.add(tf,BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
frame.setVisible(true);
}
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if(e.isPopupTrigger()) {
popup.show(e.getComponent(),
e.getX(),e.getY());
}
}
}
题目:设计如图所示弹出式菜单,界面有提示信息。点击右键弹出菜单,包括“新建”、“打开”、“保存”和“退出”四个菜单项。点击前面3个菜单选项在底部信息栏显示菜单项名,点击“退出”退出界面。
问题:我的程序还不能实现“点击‘退出’退出界面“,这要怎么改进?
在 public void go() {中添加
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
sh();
}
});
在一个类下面写个退出方法就可以了
public void sh() {
System.exit(0);
}
页:
[1]