Zeeshan Ahmed
Zeeshan Ahmed

Reputation: 20

JButton hover effect delay in Java

I want to know about these two questions.
1. I am using NetBeans and I have created a project, I already have saved all the images in "src" folder, but when I put just image name like (image.png) then no image will displayed on button. I have attached working code as well as no working code below -

Not Working Code:

 private void loginMouseEntered(java.awt.event.MouseEvent evt) {                                   
    login.setIcon(new ImageIcon("login_button_hover.png"));
}

Working Code

 private void loginMouseEntered(java.awt.event.MouseEvent evt) {                                   
    login.setIcon(new ImageIcon("C:\\Users\\Zeeshan\\Documents\\NetBeansProjects\\Attandence Software\\src\\images\\login_button_hover.png"));
}

2. I want to give delay to the "Hover" image. For example: If I take my mouse pointer to the Button/Image, the Hover image will display slowly and take 1 sec to display completely.

Upvotes: 0

Views: 287

Answers (1)

JB Nizet
JB Nizet

Reputation: 692181

Read the javadoc of the constructor:

public ImageIcon(String filename)

Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path.

(emphasis mine)

It doesn't expect a classpath resource path as argument, but a file path (i.e. the path of a file on the file system, not the path of a resource of your app).

If you want to load a resource using the ClassLoader, then use

new ImageIcon(MyClass.class.getResource("/login_button_hover.png"));

Also, you'd better load this ImageIcon once and reuse it, instead of reconstructing it every time the mouse enters the button.

Regarding your second point, you could start a swing Timer every time the mouse enters the button, and have the timer change the icon once the second is elapsed. But you'll have to deal with multiple enters per second, etc. What's wrong with setRolloverIcon()?

Upvotes: 2

Related Questions