我知道如果鼠标悬停在item1.setToolTipText("This shows up on mouse hover");
上,{{1}}将允许显示文字。我想知道我是否可以在鼠标悬停时改变图像?提前谢谢。
答案 0 :(得分:4)
我会在保存图片的组件中添加MouseListener
。
然后只需覆盖方法mouseEntered(MouseEvent e)
和mouseExited(MouseEvent e)
即可更改图片。
这是一个完整的工作示例:
public class JFrameExample {
public static void main(String[] args) throws MalformedURLException, IOException {
final JButton j;
BufferedImage imgOne = ImageIO.read(new URL("http://www.suptechnology.ma/entrepot/logocert/logocert-20130211115413.png"));
BufferedImage imgTwo = ImageIO.read(new URL("http://market.milouz.com/data/icon53.png"));
final ImageIcon imageIconOne = new ImageIcon(imgOne);
final ImageIcon imageIconTwo = new ImageIcon(imgTwo);
JFrame f = new JFrame("This is a test / Image on hover");
f.setSize(500, 500);
Container content = f.getContentPane();
content.setLayout(new FlowLayout());
j = new JButton(imageIconOne);
j.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {
j.setIcon(imageIconOne);
}
@Override
public void mouseEntered(MouseEvent arg0) {
j.setIcon(imageIconTwo);
}
@Override
public void mouseClicked(MouseEvent arg0) {}
});
content.add(j);
f.setVisible(true);
}
}
答案 1 :(得分:0)
private void SettingsMouseEntered(java.awt.event.MouseEvent evt) {
ImageIcon Setting = new ImageIcon(getClass().getResource("/pic/settings2.png"));
Settings.setIcon(Setting);
}
private void SettingsMouseExited(java.awt.event.MouseEvent evt) {
ImageIcon Setting = new ImageIcon(getClass().getResource("/pic/settings1.png"));
Settings.setIcon(Setting);
}