Spots
Spots

Reputation: 13

MenuListener not working

I am trying to create a JMenu with a MenuListener to exit when selected, but the program is not exiting.

Compiler does not show any error message. Not sure if it is the e.getsource() not working or if it is something else.

Thank you in advance.

 import java.awt.*;


import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

public class entree implements MenuListener{
    JFrame frame;
    JMenu exit,teach;
    entree(){
        Font font=new Font("SansSerif",Font.BOLD,22);
        JFrame frame=new JFrame();
        ImageIcon icon=new ImageIcon("D:\\Capture_aurora.png");
        JLabel  bg=new JLabel(icon);
        JMenuBar mb=new JMenuBar();

        JMenu teach=new JMenu("Teach");
        JMenu exit =new JMenu("Exit");
        teach.setFont(font);exit.setFont(font);exit.addMenuListener(this);teach.addMenuListener(this);

        mb.add(teach);mb.add(Box.createHorizontalGlue());mb.add(exit);


        JButton button1=new JButton("Start");
        button1.setFont(font);
        button1.setBounds(870,820,150,45);

        frame.setJMenuBar(mb);
        frame.add(button1);
        frame.add(bg,BorderLayout.CENTER);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setUndecorated(true);


        frame.setVisible(true);

    }
    public static void main(String[]args) {new entree();}

    public void menuSelected(MenuEvent e) {
        if(e.getSource()==exit) {
         System.exit(0);frame.dispose();}// Code supposed to work here, but the program won't exit
        if(e.getSource()==teach) {} 
        }

    public void menuDeselected(MenuEvent e) {

    }
    public void menuCanceled(MenuEvent e) {

    }

    }

Upvotes: 0

Views: 373

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

Answer to the question

You're shadowing your variables...

public class entree implements MenuListener {

    JFrame frame;
    JMenu exit, teach;

    entree() {
        //...
        JMenu teach = new JMenu("Teach");
        JMenu exit = new JMenu("Exit");

You're creating local variables in the constructor with the same names as the instance fields you are trying to compare later. This means that exit and teach are actually null when you try and compare them in the menuSelected event handler.

Suggestions...

Generally speaking, this really isn't how JMenus are suppose to work, they aren't meant to be "actionable" items, they are meant to be containers for like items (implemented as JMenuItems).

I would consider either using a JToolBar or JPanel with JButtons which is added to the NORTH position of a BorderLayout instead. From a user's perspective, it would make for a more common and expected user experience - IMHO

Upvotes: 2

Related Questions