简体   繁体   中英

Using ActionListener in separate class

I'm trying to make a separate class for an action listener but I'm not sure how to add the action listener to the menu item. I've been trying a few different things but none of them are letting the message dialog appear. I have the action listener in a separate class and the menu item in a separate class and I'm trying to get them to work together.

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;
    }

Another Class:

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;

    }
}

You seem to be suffering from a lot of confusion as to classes, interfaces, etc so it's actually hard to know where to begin!

First up your Listener class needs to implement ActionListener.

Then you need to add it inside your HangmanView class the same way you already are:

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
});

And that's it, you are done...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM