0

In the past few months I've tried my hand at programming in Java, and for the most part haven't had any problems with it, but right now I'm having some trouble working with voids. In my program the user presses a button and the goal is for multiple messages to be displayed on a JLabel, the messages spread out with a Thread.sleep() method. For some reason only the last one ends up being sent. Here's my code. It's not all of it, but I'm pretty sure that the problem is somewhere in here. The error outputs in there were to try and see what was going on in the code, but, obviously they didn't end up working.

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);
        }
    }
}

and

private void createNewArrayList() {
    ArrayList al = new ArrayList();
    al.add(alValue);
    label1.setText("" + al);
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
KrisC
  • 57
  • 4

2 Answers2

2

Don't call Thread.sleep() in the EDT, use a Swing Timer instead. Adjust the period interval accordingly to vary delays between System.out calls. Always use braces to clarify the scope of if statements.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

i am not sure if this is a typo but you have not defined alvalue as a member of actionperformed() function. And also in java indentation is not what measures the scope you need to put braces {}

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();
}
kaushik gandhi
  • 768
  • 8
  • 14
  • alValue is defined somewhere else in the code so no, that's definitely not the problem. I tried adding in the brackets, but the code still seems to run the same. – KrisC Dec 17 '12 at 22:15