[英]Change ImageIcon in JLabel using Timer
I have two classes: logic and the JFrame
. 我有两个类:逻辑和
JFrame
。 In frame I have a JLabel
and a JButton
, and I would like to: 在框架中,我有一个
JLabel
和一个JButton
,我想:
When this button is clicked, the ImageIcon
in the label changes after a determined time using a Swing Timer
, like if it is flashing. 单击此按钮后,标签中的
ImageIcon
在确定的时间后使用Swing Timer
,就像它正在闪烁一样。 To do it I loaded two images with different brightness ( img1b
and img1
). 为此,我加载了两个亮度不同的图像(
img1b
和img1
)。 I tried to make the timer change the image twice with different delays, but I was unsuccessful. 我试图使计时器以不同的延迟两次更改图像,但未成功。 I also put a listener in the button and implemented the
actionPerformed
as below: 我还在按钮中放置了一个侦听器,并实现了
actionPerformed
,如下所示:
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(btnImg1)) {
logic.piscaImagen(img1, lblImg1);
logic.piscaImagen(img1b, lblImg1);
In logic class: 在逻辑课中:
public void piscaImagen(ImageIcon img, JLabel lbl) {
Timer timer = new Timer(1250, null);
timer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt){
if(lbl.getIcon() != img){
lbl.setIcon(img);
}
}
});
timer.setRepeats(false);
timer.start();
}
But when I run it nothing changes in the logic.piscaImagen
. 但是,当我运行它时,
logic.piscaImagen
没有任何变化。 Any tips? 有小费吗?
logic.piscaImagen(img1, lblImg1);
logic.piscaImagen(img1b, lblImg1);
It looks to me like you are starting two Timers. 在我看来,您正在启动两个计时器。 So the first Timer fires and it changes the image, then the second timer fires and it restores the image so basically you only see the first image.
因此,第一个计时器触发并更改图像,然后第二个计时器触发并恢复图像,因此基本上您只能看到第一个图像。
All you need is one Timer. 您只需要一个计时器。 Each time the Timer fires you change the image.
每次定时器触发时,您都会更改图像。 So the basic code in your Timer would be:
因此,Timer中的基本代码为:
if (lbl.getIcon() == img1)
lbl.setIcon(img1b);
else
lbl.setIcon(img1);
Or for a more flexible solution you can use the Animated Icon . 或者,对于更灵活的解决方案,您可以使用Animated Icon 。
The Animated Icon
will allow you to specify a List of Icons to display. Animated Icon
将允许您指定要显示的图标列表。 Then when the Timer fires the next Icon in the List is displayed. 然后,当计时器触发时,将显示列表中的下一个图标。 You can set the
Animated Icon
for continuous display or you can control the number of cycles. 您可以将
Animated Icon
设置为连续显示,也可以控制循环数。
EDIT : answer inaccurate, repaint()
not necessary - see comments. 编辑 :回答不准确,不需要
repaint()
-请参阅注释。
You're missing the repaint()
call that tells the program it needs to update the display. 您错过了告诉程序需要更新显示的
repaint()
调用。
@Override
public void actionPerformed(ActionEvent evt) {
if(lbl.getIcon() != img){
lbl.setIcon(img);
lbl.repaint();
}
}
(your if
statement was also missing a closing brace, unsure what impact that would have / if it was a typo) (
if
您的语句也缺少右括号,则不确定会产生什么影响/如果是错字)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.