Yuri Yuri - 7 days ago 5
Java Question

Closing JFrame with a JButton

Im having problem with this code , it doesn't compile . Could you help me ?
I need to close the JFrame when i click the button

public class SlotMachine extends JFrame
{
/*
*
*/
JButton btnExit = new JButton("Exit");
btnExit.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent arg0)
{
this.dispose();
}
});
}


The error is = The method dispose() is undefined for the type new MouseAdapter(){}

I dont know how to get the SlotMachine object from the mouseClicked method

Answer

You're calling this.dispose(); the key here being that this refers to the inner class, the MouseListener, and MouseListener doesn't have a dispose() method.

Solution: get rid of this, and it should work, since the compiler will then look into the outer class if the inner class does not contain the method. Alternatively you could specify which this you mean: SlotMachine.this.dispose(); will tell the compiler to call the method of the outer SlotMachine class.

Use an ActionListener on a JButton for several reasons:

  • Default behavior of buttons is to be activated by spacebar press if the button has focus. This will not work for a MouseListener.
  • Also an expected behavior is that if the button is disabled via setEnabled(false), then pressing it should not cause the action to be fired. This does not work with MouseListener but does with ActionListener.
  • You can easily share the ActionListener (or better yet, an AbstractAction) with other components including JMenuItems.
Comments