简体   繁体   English

在JButton中显示图标并将其隐藏

[英]display an icon in a JButton and hide it

I have a JButton, and I want when I click to this button to display an icon in it then after 3 seconds to hide the icon and display a text in the button. 我有一个JButton,当我单击该按钮时要在其中显示一个图标,然后在3秒后隐藏该图标并在该按钮中显示文本。

in the action listener I tried this code : 在动作监听器中,我尝试了以下代码:

JButton clickedButton = (JButton) e.getSource();
clickedButton.setIcon(new ImageIcon(images.get(clickedButton.getName())));
try {
    Thread.sleep(3000);                
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}
clickedButton.setText("x");
clickedButton.setIcon(null);

The problem is that when I click in the button the program blocks for 3 minutes then the text "x" displayed in the button. 问题是,当我单击按钮时,程序将阻塞3分钟,然后在按钮中显示文本“ x”。

How can I solve this problem ? 我怎么解决这个问题 ?

Don't call Thread.sleep(...) on the Swing event thread since that freezes the thread and with it your GUI. 不要在Swing事件线程上调用Thread.sleep(...) ,因为那样会冻结线程及其GUI。 Instead use a Swing Timer . 而是使用Swing计时器 For example: 例如:

final JButton clickedButton = (JButton) e.getSource();
clickedButton.setIcon(new ImageIcon(images.get(clickedButton.getName())));

new Timer(3000, new ActionListener(){
  public void actionPerformed(ActionEvent evt) {
    clickedButton.setText("x");
    clickedButton.setIcon(null);   
    ((Timer) evt.getSource()).stop(); 
  }
}).start();

As suggested you don't need to use Thread.Sleep use Swing Timer to perform this task. 如建议的那样,您无需使用Thread.Sleep即可使用Swing Timer执行此任务。

 // Declare button and assign an Icon.
 Icon icon = new ImageIcon("search.jpg");
 JButton button = new JButton(icon);    
 ChangeImageAction listener = new ChangeImageAction(button);
 button.addActionListener(listener);

Below ChangeImageAction class will do the necessary action when the button is clicked. 单击该按钮时,在ChangeImageAction类下面将执行必要的操作。 When you click on the button an action is fired and in this action we will call the Timer's Action listener where we set the button's icon as null and give the button a title. 当您单击按钮时,将触发一个动作,并且在此动作中,我们将调用Timer的Action侦听器,在此将按钮的图标设置为null并为按钮命名。

class ChangeImageAction implements ActionListener {

    private JButton button;

    public ChangeImageAction(JButton button) {
        this.button = button;
    }

    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            button.setIcon(null);
            button.setText("Button");
        }
    };

    @Override
    public void actionPerformed(ActionEvent arg0) {
        Timer timer = new Timer( 3000 , taskPerformer);
        timer.setRepeats(false);
        timer.start();
    }

}

PS: I am trying Timer for the first time thanks to @Hovercraft Full Of Eels for the suggestion. PS:感谢@Hovercraft Full Of Eels的建议,我第一次尝试使用Timer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM