I have a JFrame
with a JPanel
of FlowLayout
. A JButton
is placaed on the panel. I want the JFrame to be closed whenever mouse is moved out of the JFrame. It works fine.
But it does the same even when the mouse moves onto the JButton
!! And I dont want that!
Code of JFrame Class, MyFrame.java
:
import javax.swing.*;
import java.awt.event.*;
public class MyFrame extends JFrame {
JButton btnOne; JPanel panOne;
public MyFrame() {}
public MyFrame() {
this.setSize(400, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.initComps();
this.setFrameMouseActions();
this.setVisible(true);
}
public void initComps() {
panOne = new JPanel();
btnOne = new JButton("Click Me!");
panOne.add(btnOne);
this.add(panOne);
}
public void setFrameMouseActions() {
this.addMouseListener(new MouseListener() {
public void mouseExited(MouseEvent e) {
dispose();
JOptionPane.showMessageDialog(null, "Disposed", "Disposed", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
});
}
}
Code of Main Class, MouseMain.java
:
public class MouseMain {
public static void main(String[] args) {
MyFrame frameOb = new MyFrame();
}
}
NOTE: I have tried with null layout
too(although its bad practice!). But its all the same. And this code is a simplified version from a large project of mine.