【发布时间】:2014-01-02 18:27:55
【问题描述】:
我正在尝试将 .gif 文件添加到 JButton 中,但似乎不起作用 - gif 文件没有移动,它像普通图像一样显示。
这是我的代码:
+ImageButton 类:
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
/**
* Button which display a png or gif image.
* */
public class ImageButton extends JButton {
private static final long serialVersionUID = 1L;
private ImageIcon defaultIcon;
private ImageIcon hoverIcon;
/**
* Create a normal JButton.
* */
public ImageButton(){
super();
}
/**
* Create a new ImageButton Object.
* @param img1 url of normal image of the button
* @param img2 url hover image of the button
* @param width button width
* @param height button height
* */
public ImageButton(String img1, String img2, int width, int height){
super();
BufferedImage defaultIcon = null;
BufferedImage hoverIcon = null;
try {
defaultIcon = ImageIO.read(getClass().getResource(img1));
hoverIcon = ImageIO.read(getClass().getResource(img2));
} catch (IOException e) {
e.printStackTrace();
}
this.defaultIcon = new ImageIcon(defaultIcon);
this.hoverIcon = new ImageIcon(hoverIcon);
setIcon(this.defaultIcon);
setPreferredSize(new Dimension(width,height));
setBorder(null);
setOpaque(false);
setContentAreaFilled(false);
setBorderPainted(false);
}
/**
* Hover the button.
* */
public void hover(){
setIcon(hoverIcon);
}
/**
* Return the button to normal.
* */
public void down(){
setIcon(defaultIcon);
}
}
+测试类: 导入 java.awt.FlowLayout;
import javax.swing.JFrame;
public class TestGifButton {
public static void main(String[] args) {
ImageButton button = new ImageButton("level3.gif","level3.gif", 150, 150);
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}
我使用了一个循环的 .gif 文件。
那么我该如何解决呢?非常感谢:'(
【问题讨论】:
-
它不能回答我的问题 - gif 文件可以轻松显示在 JLabel 上,但不能显示在我的 JButton 中。
-
read post about @MadProgrammer
-
不要继承 JButton,如果是则覆盖在 Api 中实现的 set(Xxx)Icon
标签: java eclipse swing jbutton animated-gif