我有一个 JButton
,我在上面设置了一个自定义图标。现在当我拖动鼠标指针时,我希望它显示另一个图标,但我不知道该如何实现,因为如果我使用 button.setIcon(icon);
,它将替换已经显示的图标。有什么尽可能简单的方法可以做到这一点吗?
我认为你可以使用
JButton.setRolloverIcon(myIcon);
JButton在API中实现了这些方法。
JButton.setIcon(myIcon);
JButton.setRolloverIcon(myIcon);
JButton.setPressedIcon(myIcon);
JButton.setDisabledIcon(myIcon);
如果您的图标已经是透明的,您可以轻松地实现自己的Icon
来结合这两个元素 -
public class CombineIcon implements Icon {
private Icon top;
private Icon bottom;
public CombineIcon(Icon top, Icon bottom) {
this.top = top;
this.bottom = bottom;
}
public int getIconHeight() {
return Math.max(top.getIconHeight(), bottom.getIconHeight());
}
public int getIconWidth() {
return Math.max(top.getIconWidth(), bottom.getIconWidth());
}
public void paintIcon(Component c, Graphics g, int x, int y) {
bottom.paintIcon(c, g, x, y);
top.paintIcon(c, g, x, y);
}
}
setRolloverIcon(icon)
来指定当鼠标悬停在按钮上时要显示的图标。import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
class CombinedIconButton {
public static BufferedImage getCombinedImage(BufferedImage i1, BufferedImage i2) {
if (i1.getHeight() != i2.getHeight()
|| i1.getWidth() != i2.getWidth()) {
throw new IllegalArgumentException("Images are not the same size!");
}
BufferedImage bi = new BufferedImage(
i1.getHeight(),
i1.getWidth(),
BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
g.drawImage(i1,0,0,null);
g.drawImage(i2,0,0,null);
g.dispose();
return bi;
}
public static void main(String[] args) throws Exception {
URL url1 = new URL("http://i.stack.imgur.com/gJmeJ.png"); // blue circle
URL url2 = new URL("http://i.stack.imgur.com/5v2TX.png"); // red triangle
final BufferedImage bi1 = ImageIO.read(url1);
final BufferedImage bi2 = ImageIO.read(url2);
final BufferedImage biC = getCombinedImage(bi1,bi2);
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
JToggleButton b = new JToggleButton();
b.setIcon(new ImageIcon(bi1));
b.setRolloverIcon(new ImageIcon(biC));
b.setSelectedIcon(new ImageIcon(bi2));
gui.add(b);
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
图片来源于 this answer。
一种方法是:
使用某些图像编辑工具创建一个图标,当指针悬停在按钮上方时,您想要看到该图标。并在鼠标悬停事件发生时设置该图像。
附:使用任何图片编辑工具,您都可以轻松创建覆盖图像。
我还看到了AbstractButton类中的“滚动图标”概念。您也可以使用它。
JButton
,当我悬停在它们上面时,我希望第二个图标出现,因此我需要4张图片而不是3张。 - user2328614