在Java中使用多个空洞

在Java中使用多个空洞,java,swing,concurrency,jlabel,event-dispatch-thread,Java,Swing,Concurrency,Jlabel,Event Dispatch Thread,在过去的几个月里,我尝试了用Java编程,大部分时间都没有遇到任何问题,但现在我在处理voids时遇到了一些问题。在我的程序中,用户按下一个按钮,目标是在JLabel上显示多条消息,这些消息通过Thread.sleep()方法分散开来。由于某种原因,只有最后一个最终被发送。这是我的密码。这不是全部,但我很确定问题在这里的某个地方。其中的错误输出是为了尝试看看代码中发生了什么,但是,很明显,它们最终没有起作用 private class ClickListener implements Actio

在过去的几个月里,我尝试了用Java编程,大部分时间都没有遇到任何问题,但现在我在处理voids时遇到了一些问题。在我的程序中,用户按下一个按钮,目标是在JLabel上显示多条消息,这些消息通过Thread.sleep()方法分散开来。由于某种原因,只有最后一个最终被发送。这是我的密码。这不是全部,但我很确定问题在这里的某个地方。其中的错误输出是为了尝试看看代码中发生了什么,但是,很明显,它们最终没有起作用

private class ClickListener implements ActionListener 
{    
    public void actionPerformed(ActionEvent e)
    {
        try {
            if (e.getSource() == exitButton)
                System.exit(0);

            else if (e.getSource() == button1)
                alValue = "This is the new message text.";
            System.err.println(alValue);
            createNewArrayList();
            Thread.sleep(3000);
            alValue = "Back to invisible...";
            System.err.println(alValue);
            createNewArrayList();
            Thread.sleep(2000);
            alValue = "";
            System.err.println(alValue);
            createNewArrayList();
        } catch (InterruptedException ex) {
            Logger.getLogger(EmptySpace.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


我不确定这是否是输入错误,但您尚未将alvalue定义为actionperformed()函数的成员。 而且在java缩进中,并不是用来度量放大括号{}所需的范围的

if (e.getSource() == button1)
  {
                 alValue = "This is the new message text.";
                 System.err.println(alValue);
                 createNewArrayList();
                 Thread.sleep(3000);
                 alValue = "Back to invisible...";
                 System.err.println(alValue);
                 createNewArrayList();
                 Thread.sleep(2000);
                 alValue = "";
                 System.err.println(alValue);
                 createNewArrayList();
}

不要在
EDT
中调用
Thread.sleep()。相应地调整时段间隔,以改变
System.out
调用之间的延迟。始终使用大括号来澄清
if
语句的范围。

您所说的“处理空洞”是什么意思?是否显示了“返回到不可见…”值?@Amar,不,我没有在JLabel上显示该值。只显示最后一个。alValue是在代码中的其他地方定义的,所以不,这绝对不是问题所在。我尝试在括号中添加,但代码似乎仍然运行相同的。好的,它与swing计时器完美配合。谢谢你的帮助!
if (e.getSource() == button1)
  {
                 alValue = "This is the new message text.";
                 System.err.println(alValue);
                 createNewArrayList();
                 Thread.sleep(3000);
                 alValue = "Back to invisible...";
                 System.err.println(alValue);
                 createNewArrayList();
                 Thread.sleep(2000);
                 alValue = "";
                 System.err.println(alValue);
                 createNewArrayList();
}