Java swing:选择/取消选择JButton来模仿脉冲

bun*_*112 0 java swing selection jbutton

我有一个电子邮件客户端,它收到新消息,带有传入消息的按钮开始做某事,直到用户点击它看到最新消息.

我试图通过选择,等待然后取消选择使按钮吸引注意力,但这没有任何作用!

 do{
        button.setSelected(true);
               Thread oThread = new Thread() {
                    @Override
                   public void run() {
                       synchronized (this) {
                           try {
                               wait(1000);
                           } catch (InterruptedException e1) {
                               e1.printStackTrace();
                           }
                       }
                       button.setSelected(false);
                   }
               };
               oThread.start();
        }while(true);
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 5

你应该使用Swing计时器.不要与外部线程的GUI对象进行交互.

Java教程中有一些文档:如何使用Swing计时器.

这是一个使用按钮图标播放的示例方法.

// member var
Icon buttonIcon;
Timer timer;
Run Code Online (Sandbox Code Playgroud)
  // in constructor for example
  buttonIcon = new ImageIcon("resources/icon.png");
  button.setIcon(buttonIcon);

  timer = new Timer(1000, this);
  timer.start();
Run Code Online (Sandbox Code Playgroud)
   // in the actionPerformed handler
   if (button.getIcon() == null)
     button.setIcon(icon);
   else
     button.setIcon(null);
Run Code Online (Sandbox Code Playgroud)

你的班级需要实现ActionListener这样的工作.添加一些逻辑以在需要时停止闪烁.