Reputation: 103
I have seen many questions similar to this But I am not able to understand why the repaint do not work properly
In my program Before exiting the Frame I called repaint() use Thread.sleep to delay the exit then also the msg "Mouse Exited" does not get displayed.
Can you please explain why this happens or provide the link for the same
public void mouseExited(MouseEvent me)
{
msg="Mouse Exited";
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.exit(0);
}
Complete Program
/**Write a program to create a frame using AWT. Implement mouseClicked( ),
mouseEntered( ) and mouseExited( ) events. Frame should become visible when
mouse enters it. */
import java.awt.*;
import java.awt.event.*;
class Question8 extends Frame{
static Dimension original;
String msg;
Question8(String s)
{
msg=s;
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
msg="Mouse Clicked";
setSize(original);
repaint();
}
public void mouseEntered(MouseEvent me)
{
msg="Mouse Entered";
setSize(original.height*3,original.width*3);
repaint();
}
public void mouseExited(MouseEvent me)
{
msg="Mouse Exited";
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.exit(0);
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(Window ev)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.drawString(msg, 50, 50);
}
public static void main(String agrs[])
{
Question8 obj=new Question8("Hello");
original=new Dimension(300,300);
obj.setSize(original);
obj.setTitle("Question 8");
obj.setVisible(true);
}
}
Upvotes: 0
Views: 79
Reputation: 11411
As maloomeister pointed out, the Thread.sleep()
is blocking the event thread, so you need to create a new thread.
If you replace your mouseExited
method with this it will behave as you expect:
public void mouseExited(MouseEvent me) {
msg = "Mouse Exited";
repaint();
new Thread(() -> {
try {
Thread.sleep(1000);
System.exit(0);
} catch (InterruptedException e) {
}
}
).start();
}
Upvotes: 2