gpt4 book ai didi

java - 在单独的类中使用 ActionListener

转载 作者:行者123 更新时间:2023-12-02 06:23:10 26 4
gpt4 key购买 nike

我正在尝试为操作监听器创建一个单独的类,但我不确定如何将操作监听器添加到菜单项。我一直在尝试一些不同的事情,但没有一个让消息对话框出现。我将 Action 监听器放在一个单独的类中,将菜单项放在一个单独的类中,我试图让它们一起工作。

public class HangmanView {
Listener listener = new Listener();

public JMenuItem getMenuItem() {
JMenuItem menuItem = new JMenuItem("Developer", KeyEvent.VK_T);
menuItem.addActionListener(new Listener());
return menuItem;
}

public JMenuBar menuBar() {

JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
menu.add(getMenuItem());
return menuBar;
}

另一类:

public class Listener {
JFrame dialogFrame = new JFrame();

public JFrame menuItemListener() {
HangmanView hangmanView = new HangmanView();

hangmanView.getMenuItem().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {// right click key
JOptionPane.showMessageDialog(dialogFrame, "Developer: Joe"
, "Developer",
JOptionPane.INFORMATION_MESSAGE);
}// end actionPerformed method
});
return dialogFrame;

}
}

最佳答案

您似乎对类、接口(interface)等感到很多困惑,因此实际上很难知道从哪里开始!

首先,您的 Listener 类需要实现 ActionListener。

然后您需要将其添加到您的 HangmanView 类中,就像您已经这样做的那样:

public class Listener implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {// right click key
JOptionPane.showMessageDialog(dialogFrame, "Developer: Joe"
, "Developer",
JOptionPane.INFORMATION_MESSAGE);
}// end actionPerformed method
});

就这样,你就完成了......

关于java - 在单独的类中使用 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20819453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com