Update JLabel every X seconds from ArrayList - Java

前端 未结 4 1612
-上瘾入骨i
-上瘾入骨i 2020-11-22 10:17

I have a simple Java program that reads in a text file, splits it by \" \" (spaces), displays the first word, waits 2 seconds, displays the next... etc... I would like to do

4条回答
  •  长发绾君心
    2020-11-22 10:36

    You're on the right track, but you're creating the frame's inside the loop, not outside. Here's what it should be like:

    private void printWords() {
        JFrame frame = new JFrame("Run Text File"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        JLabel textLabel = new JLabel("", SwingConstants.CENTER);
        textLabel.setPreferredSize(new Dimension(300, 100)); 
        frame.getContentPane().add(textLabel, BorderLayout.CENTER);
        //Display the window. frame.setLocationRelativeTo(null); 
        frame.pack(); 
        frame.setVisible(true);
    
        for (int i = 0; i < words.size(); i++) {
            //How many words?
            //System.out.print(words.size());
            //print each word on a new line...
            Word w = words.get(i);
            System.out.println(w.name);
    
            //pause between each word.
            try{
                Thread.sleep(500);
            } 
            catch(InterruptedException e){
                e.printStackTrace();
            }
            textLabel.setTest(w.name);
        }
    }
    

提交回复
热议问题