0

在过去的几个月里,我尝试过用 Java 编程,而且大部分都没有遇到任何问题,但现在我在处理 void 时遇到了一些麻烦。在我的程序中,用户按下一个按钮,目标是在 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);
        }
    }
}

private void createNewArrayList() {
    ArrayList al = new ArrayList();
    al.add(alValue);
    label1.setText("" + al);
}
4

2 回答 2

2

不要调用Thread.sleep(),而是EDT使用 Swing Timer。相应地调整周期间隔以改变System.out呼叫之间的延迟。始终使用大括号来阐明if语句的范围。

于 2012-12-17T22:11:58.747 回答
0

我不确定这是否是一个错字,但您尚未将 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();
}
于 2012-12-17T22:08:06.550 回答