gpt4 book ai didi

java - 在 mouseMove 上设置 jLabel 的图标并随时间更改图像

转载 作者:行者123 更新时间:2023-12-01 13:30:53 25 4
gpt4 key购买 nike

我正在使用 netbeans,并且我有一个 jLabel,当鼠标重叠在按钮上时(当您要单击时),它会更改图标。我的代码:

private void BtnRoomsMouseMoved(java.awt.event.MouseEvent evt) {                                    
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/at/rosom.jpg")));
}

只要鼠标仍然重叠在按钮上,我就想让它及时改变。这使它看起来像一个屏幕保护程序。我的想法是我应该使用 Thread.sleep() ,但我不知道它的正确用法。请帮忙。

最佳答案

不要尝试使用MouseListener,只需使用按钮翻转功能

button.setIcon(icon);
button.setRolloverEnabled(true);

// create an instance of the RolloverIcon class when calling setRolloverIcon
button.setRolloverIcon(rollOverIcon);

不需要计时器或任何东西。运行简单的例子

import java.net.*;
import java.util.logging.*;
import javax.swing.*;

public class ButtonRollover {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
ImageIcon rollover = new ImageIcon(new URL("https://trustcloud.com/images/homepage-icon-source-stackoverflow.png"));
ImageIcon icon = new ImageIcon(new URL("http://www.pixelearth.net/images/icons/stackoverflow.png"));

JButton button = new JButton(icon);
button.setRolloverEnabled(true);
button.setRolloverIcon(rollover);

JOptionPane.showMessageDialog(null, button, "Rollover", JOptionPane.PLAIN_MESSAGE);
} catch (MalformedURLException ex) {
Logger.getLogger(ButtonRollover.class.getName()).log(Level.SEVERE, null, ex);
}
}

});
}
}
<小时/>

编辑

从这个 BtnRoomsMouseMoved 的外观来看,您似乎在应该使用 MouseListener 时使用了 MouseMotionListener。右键单击按钮时,不要选择 MouseMotion,而是选择 Mouse,并且您需要同时实现 mouseEnteredmouseExited >。您可以在这些方法中来回更改标签图标。

运行此示例

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.*;
import java.util.logging.*;
import javax.swing.*;

public class ButtonRollover {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
final ImageIcon rollover = new ImageIcon(new URL("https://trustcloud.com/images/homepage-icon-source-stackoverflow.png"));
final ImageIcon icon = new ImageIcon(new URL("http://www.pixelearth.net/images/icons/stackoverflow.png"));

final JLabel label = new JLabel(icon);

JButton button = new JButton("Change Image");
button.addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent e) {
label.setIcon(rollover);
}
public void mouseExited(MouseEvent e) {
label.setIcon(icon);
}
});

JPanel panel = new JPanel();
panel.add(label);
panel.add(button);

JOptionPane.showMessageDialog(null, panel, "Rollover", JOptionPane.PLAIN_MESSAGE);
} catch (MalformedURLException ex) {
Logger.getLogger(ButtonRollover.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}

关于java - 在 mouseMove 上设置 jLabel 的图标并随时间更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21577360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com