如何在单击按钮时在两个图像之间切换,然后在再次单击时停止,Java?

时间:2014-05-21 01:43:31

标签: java multithreading swing actionlistener

所以,我有三个类用于表示一个程序,当点击on按钮时,该程序假设在灯泡图像和关闭灯泡图像之间交替,然后切换到关闭按钮图像。 ;再次点击。最初,当程序启动时,它的默认设置为ON,但它保持为ON图像并且不会交替,当你按下按钮两次时,程序就会冻结(我猜它会创建一个无限循环)。这是我用来处理Button监听器的代码(它是我用来创建按钮并将它们添加到面板的类中的嵌套类):

private class OnListener implements ActionListener
{
    //--------------------------------------------------------------
    //  Turns the bulb on and repaints the bulb panel.
    //--------------------------------------------------------------
    public void actionPerformed (ActionEvent event)
    {
        if (bulb.isOn()){
            bulb.setOn (false);
            bulb.repaint();
            onButton.setText("Off");
            onButton.setMnemonic ('O');
            add (onButton);
        }
        else{
            bulb.setOn (true);
            onButton.setText("On");
            onButton.setMnemonic ('n');
            add(onButton);

            while (bulb.isOn()){
                bulb.repaint();
                try{
                    Thread.sleep(1000);
                }
                catch (InterruptedException e){
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你有一个while (true)循环和一个Thread.sleep语句,两者都会绑定和Swing事件线程,冻结你的GUI,一个常见的问题和这个和其他类似网站上的常见问题。

解决方案:使用javax.swing.Timer,也称为Swing Timer。在Timer中通过JLabel的setIcon(icon)方法交换JLabel的ImageIcon。

如,

  int delay = 1000;
  final Timer timer = new Timer(delay, new ActionListener() {

     @Override
     public void actionPerformed(ActionEvent e) {
        // TODO put in code to repeat
        // including swapping a JLabel's image icon
     }
  });
  JButton btn = new JButton("Foo");
  btn.addActionListener(new ActionListener() {

     @Override
     public void actionPerformed(ActionEvent arg0) {
        timer.start(); // or stop if you want to stop the swapping
     }
  });