java - swing GUI 组件的计时器问题

标签 java swing scala timer

这段代码在点击时基本上会显示卡片的背面。 showFace 函数设置图标和文本,从而暗示卡片的正面。浅灰色背景是背面。如果点击了不匹配的卡片,我首先打算 showFace 短暂(2 秒),然后恢复到“卡片的背面”。但是,单击不匹配的卡片后,图标和文本会立即闪烁并恢复为灰色背景。

尝试将 2000 毫秒更改为更高的值,但无济于事。如有任何帮助,我们将不胜感激。

else if (currentMode == 1){
  //matched cards
  if(checkCards(currentCard, names)){
    showFace();
    currentMode = 0;
    currentCard = "";
    deafTo(this);
  }
  //else non match, still checking mode
  else{
    showFace();
    var timer: Timer = null;
    val action = new ActionListener(){

      override def actionPerformed(event : ActionEvent){
        icon = null;
        text = "";
        background = Color.DARK_GRAY;
        timer.stop();
      }
    };
    timer = new Timer (2000, action);
    timer.setInitialDelay(0);
    timer.start();
  }
}

def showFace()={
  text = names;
  horizontalTextPosition = Alignment.Center;
  verticalTextPosition = Alignment.Bottom;
  background = Color.WHITE;
  val icons = new ImageIcon(path);
  val newIc = icons.getImage();
  val newIcons = newIc.getScaledInstance(100, 75, 
      java.awt.Image.SCALE_SMOOTH);
  icon = new ImageIcon(newIcons);
  repaint();
}

最佳答案

这是因为你在构造函数中设置了2000ms的初始延迟

timer = new Timer(2000, action)

但是你可以通过以下方式将其覆盖为 0ms:

timer.setInitialDelay(0);

删除这一行,你应该就好了。

您可以查看here Swing 定时器 API。
并查看一些示例 here .

关于java - swing GUI 组件的计时器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34013625/

相关文章:

java - JFreeChart合并DomainXYPlot - 维护绘图的顺序

java - 添加图像时 JFrame 不起作用

java - 在java中设计GUI组件的方法

java - 从另一个 JFrame 调用 JFrame 方法

scala - 按名称获取已注册的 Spark Accumulator

Scala/Akka 语法

multithreading - scala notify() 与 notifyAll()

java - 如何通过不同的进程同时在两个线程中进行处理?

java - 获取相对于 View 的触摸坐标(ScreenToClient 等效?)

java - Java 中清理线程/后台线程或进程/服务