سؤال

Below I have the following code, so that when someone clicks on the "Close", the window will close. Below that is another exit button on the same menu bar, simply for redundancy (it'll be changed later to be something else, but the point stands as follows). My question is, is there any way to make this more simplistic? I mean there are four unused methods for every menu, and I'm going to need to do a few more. Any ideas on how to fix this?

closeFile.addMouseListener(new MouseListener() {

                public void mouseClicked(MouseEvent arg0) {
                    System.exit(0);

                }

                public void mouseEntered(MouseEvent e) {


                }

                public void mouseExited(MouseEvent e) {


                }

                public void mousePressed(MouseEvent e) {


                }

                public void mouseReleased(MouseEvent e) {


                }

            });

            exit.addMouseListener(new MouseListener() {

                public void mouseClicked(MouseEvent arg0) {
                    System.exit(0);

                }

                public void mouseEntered(MouseEvent e) {


                }

                public void mouseExited(MouseEvent e) {


                }

                public void mousePressed(MouseEvent e) {


                }

                public void mouseReleased(MouseEvent e) {


                }

            });

Also, ActionListener wouldn't work for me, so I can't use that (don't believe I'm supposed to either).

هل كانت مفيدة؟

المحلول

Use a MouseAdapter and override the methods that you want.

closeFile.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent arg0) {
            System.exit(0);
        }
    });

نصائح أخرى

closeFile.addMouseListener(new MouseAdapter(){
     public void mouseClicked(MouseEvent e) {
        //your code
     }                
  });

Note: You dont have to write 'implements MouseListener' during class definition. For more information, search for adapter classes, more specifically for MouseAdapter class.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top