java实现菜单监听事件实现多个ActionEvent
时间: 2024-03-25 14:35:57 浏览: 44
Java 实现菜单监听事件(MenuListener)可以通过实现多个 ActionEvent 来实现多个事件的处理。每个 ActionEvent 将被分配一个唯一的标识符,以便您可以确定哪个事件已被触发。
下面是一个简单的示例代码,演示如何使用 MenuListener 监听菜单事件并实现多个 ActionEvent:
```java
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class MenuListenerExample extends JFrame implements MenuListener {
private final int NEW_FILE = 1;
private final int OPEN_FILE = 2;
private final int SAVE_FILE = 3;
public MenuListenerExample() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.addMenuListener(this);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new MenuListenerExample();
}
@Override
public void menuSelected(MenuEvent e) {
JMenu menu = (JMenu) e.getSource();
if (menu.getText().equals("File")) {
JMenuItem newFile = new JMenuItem("New File");
newFile.setActionCommand(String.valueOf(NEW_FILE));
newFile.addActionListener(this::actionPerformed);
menu.add(newFile);
JMenuItem openFile = new JMenuItem("Open File");
openFile.setActionCommand(String.valueOf(OPEN_FILE));
openFile.addActionListener(this::actionPerformed);
menu.add(openFile);
JMenuItem saveFile = new JMenuItem("Save File");
saveFile.setActionCommand(String.valueOf(SAVE_FILE));
saveFile.addActionListener(this::actionPerformed);
menu.add(saveFile);
}
}
@Override
public void menuDeselected(MenuEvent e) {}
@Override
public void menuCanceled(MenuEvent e) {}
public void actionPerformed(ActionEvent e) {
switch (Integer.parseInt(e.getActionCommand())) {
case NEW_FILE:
System.out.println("New File");
break;
case OPEN_FILE:
System.out.println("Open File");
break;
case SAVE_FILE:
System.out.println("Save File");
break;
default:
System.out.println("Unknown Event");
break;
}
}
}
```
在这个例子中,我们创建了一个 JMenu 对象,并在菜单被选中时,创建了三个 JMenuItem 对象,并将它们添加到了菜单中。每个 JMenuItem 对象都分配了一个唯一的标识符,并使用 setActionCommand 方法将其设置为相应的事件类型。每个 JMenuItem 对象还使用 addActionListener 方法将监听器与相应的事件处理方法关联起来。
在 actionPerformed 方法中,我们使用 switch 语句根据事件类型执行相应的操作。在本例中,我们输出了相应的消息,但您可以根据需要执行任何操作。
阅读全文
相关推荐















