从ArrayList每隔X秒更新一次JLabel<;列表>;-JAVA

从ArrayList每隔X秒更新一次JLabel<;列表>;-JAVA,java,swing,concurrency,timer,freeze,Java,Swing,Concurrency,Timer,Freeze,我有一个简单的Java程序,它读入一个文本文件,按“”分隔(空格),显示第一个单词,等待2秒钟,显示下一个。。。等我想在春季或其他GUI中这样做 关于如何使用spring轻松更新单词,有什么建议吗?遍历我的列表并以某种方式使用setText() 我一点运气都没有。我正在使用此方法在控制台中打印我的文字,并将JFrame添加到其中。。。在控制台中工作得很好,但会产生无限的jframe。我在网上找到了大部分 private void printWords() { for (i

我有一个简单的Java程序,它读入一个文本文件,按“”分隔(空格),显示第一个单词,等待2秒钟,显示下一个。。。等我想在春季或其他GUI中这样做

关于如何使用spring轻松更新单词,有什么建议吗?遍历我的列表并以某种方式使用setText()

我一点运气都没有。我正在使用此方法在控制台中打印我的文字,并将JFrame添加到其中。。。在控制台中工作得很好,但会产生无限的jframe。我在网上找到了大部分

    private void printWords() {
        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();
            }
         JFrame frame = new JFrame("Run Text File"); 
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
         JLabel textLabel = new JLabel(w.name,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);
        }
    }

到达那里。。。一旦我,或者任何人帮助我,让它工作起来,我就会发布修复。再次感谢

您在正确的轨道上,但您创建的帧在循环内部,而不是外部。下面是它应该是什么样子:

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);
    }
}
private void printWords(){
JFrame=newjframe(“运行文本文件”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textlab=新的JLabel(“,SwingConstants.CENTER);
textLabel.setPreferredSize(新尺寸(300100));
frame.getContentPane().add(textLabel,BorderLayout.CENTER);
//显示window.frame.setLocationRelativeTo(空);
frame.pack();
frame.setVisible(true);
for(int i=0;i
首先,构建并显示GUI。显示GUI后,使用每500毫秒更新一次GUI:

final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListsner() {
    private Iterator<Word> it = words.iterator();
    @Override 
    public void actionPerformed(ActionEvent e) {
        if (it.hasNext()) {
            label.setText(it.next().getName());
        }
        else {
            timer.stop();
        }
    }
};
timer.addActionListener(listener);
timer.start();
final Timer=新定时器(500,空);
ActionListener侦听器=新建ActionListsner(){
私有迭代器it=words.Iterator();
@凌驾
已执行的公共无效操作(操作事件e){
if(it.hasNext()){
label.setText(it.next().getName());
}
否则{
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();

切勿在Swing代码中使用
线程睡眠(int)
,因为它会阻止EDT;更

使用
Thread.sleep(int)
的结果如下:

线程睡眠(int)
结束时

示例代码:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.*;
//http://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java
public class ButtonsIcon extends JFrame implements Runnable {

    private static final long serialVersionUID = 1L;
    private Queue<Icon> iconQueue = new LinkedList<Icon>();
    private JLabel label = new JLabel();
    private Random random = new Random();
    private JPanel buttonPanel = new JPanel();
    private JPanel labelPanel = new JPanel();
    private Timer backTtimer;
    private Timer labelTimer;
    private JLabel one = new JLabel("one");
    private JLabel two = new JLabel("two");
    private JLabel three = new JLabel("three");
    private final String[] petStrings = {"Bird", "Cat", "Dog",
        "Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
    private boolean runProcess = true;
    private int index = 1;
    private int index1 = 1;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ButtonsIcon t = new ButtonsIcon();
            }
        });
    }

    public ButtonsIcon() {
        iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));

        one.setFont(new Font("Dialog", Font.BOLD, 24));
        one.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        two.setFont(new Font("Dialog", Font.BOLD, 24));
        two.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        three.setFont(new Font("Dialog", Font.BOLD, 10));
        three.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelPanel.setLayout(new GridLayout(0, 3, 4, 4));

        labelPanel.add(one);
        labelPanel.add(two);
        labelPanel.add(three);
        //labelPanel.setBorder(new LineBorder(Color.black, 1));
        labelPanel.setOpaque(false);

        JButton button0 = createButton();
        JButton button1 = createButton();
        JButton button2 = createButton();
        JButton button3 = createButton();

        buttonPanel.setLayout(new GridLayout(0, 4, 4, 4));
        buttonPanel.add(button0);
        buttonPanel.add(button1);
        buttonPanel.add(button2);
        buttonPanel.add(button3);
        //buttonPanel.setBorder(new LineBorder(Color.black, 1));
        buttonPanel.setOpaque(false);

        label.setLayout(new BorderLayout());
        label.add(labelPanel, BorderLayout.NORTH);
        label.add(buttonPanel, BorderLayout.SOUTH);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));

        add(label, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
        startBackground();
        startLabel2();
        new Thread(this).start();
        printWords(); // generating freeze Swing GUI durring EDT
    }

    private JButton createButton() {
        JButton button = new JButton();
        button.setBorderPainted(false);
        button.setBorder(null);
        button.setFocusable(false);
        button.setMargin(new Insets(0, 0, 0, 0));
        button.setContentAreaFilled(false);
        button.setIcon(nextIcon());
        button.setRolloverIcon(nextIcon());
        button.setPressedIcon(nextIcon());
        button.setDisabledIcon(nextIcon());
        nextIcon();
        return button;
    }

    private Icon nextIcon() {
        Icon icon = iconQueue.peek();
        iconQueue.add(iconQueue.remove());
        return icon;
    }

    // Update background at 4/3 Hz
    private void startBackground() {
        backTtimer = new javax.swing.Timer(750, updateBackground());
        backTtimer.start();
        backTtimer.setRepeats(true);
    }

    private Action updateBackground() {
        return new AbstractAction("Background action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setIcon(new ImageIcon(getImage()));
            }
        };
    }

    // Update Label two at 2 Hz
    private void startLabel2() {
        labelTimer = new javax.swing.Timer(500, updateLabel2());
        labelTimer.start();
        labelTimer.setRepeats(true);
    }

    private Action updateLabel2() {
        return new AbstractAction("Label action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                two.setText(petStrings[index]);
                index = (index + 1) % petStrings.length;
            }
        };
    }

    // Update lable one at 3 Hz
    @Override
    public void run() {
        while (runProcess) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    one.setText(petStrings[index1]);
                    index1 = (index1 + 1) % petStrings.length;
                }
            });
            try {
                Thread.sleep(300);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // Note: blocks EDT
    private void printWords() {
        for (int i = 0; i < petStrings.length; i++) {
            String word = petStrings[i].toString();
            System.out.println(word);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            three.setText(word);
        }
        three.setText("<html> Concurency Issues in Swing<br>"
                + " never to use Thread.sleep(int) <br>"
                + " durring EDT, simple to freeze GUI </html>");
    }

    public BufferedImage getImage() {
        int w = label.getWidth();
        int h = label.getHeight();
        GradientPaint gp = new GradientPaint(0f, 0f, new Color(
                127 + random.nextInt(128),
                127 + random.nextInt(128),
                127 + random.nextInt(128)),
                w, w,
                new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        g2d.setColor(Color.BLACK);
        return bi;
    }
}
import java.awt.*;
导入java.awt.event.ActionEvent;
导入java.awt.image.buffereImage;
导入java.util.LinkedList;
导入java.util.Queue;
导入java.util.Random;
导入javax.swing.*;
//http://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java
公共类ButtonsIcon扩展JFrame实现Runnable{
私有静态最终长serialVersionUID=1L;
专用队列iconQueue=new LinkedList();
专用JLabel标签=新JLabel();
私有随机=新随机();
private JPanel buttonPanel=new JPanel();
private JPanel labelPanel=new JPanel();
私人定时器倒计时器;
私人定时器;
私有JLabel one=新JLabel(“one”);
私有JLabel two=新JLabel(“two”);
私有JLabel三=新JLabel(“三”);
私有最终字符串[]petStrings={“鸟”、“猫”、“狗”,
“兔子”、“猪”、“鱼”、“马”、“牛”、“蜜蜂”、“臭鼬”};
私有布尔runProcess=true;
私有int指数=1;
私有int index1=1;
公共静态void main(字符串[]args){
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
ButtonsIcon t=新ButtonsIcon();
}
});
}
公共按钮图标(){
iconQueue.add(UIManager.getIcon(“OptionPane.errorIcon”);
iconQueue.add(UIManager.getIcon(“OptionPane.informationIcon”);
iconQueue.add(UIManager.getIcon(“OptionPane.warningIcon”);
iconQueue.add(UIManager.getIcon(“OptionPane.questionIcon”);
一.setFont(新字体(“Dialog”,Font.BOLD,24));
setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
2.setFont(新字体(“Dialog”,Font.BOLD,24));
setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
三、setFont(新字体(“Dialog”,Font.BOLD,10));
setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
setLayout(新的GridLayout(0,3,4,4));
标签面板。添加(一个);
标签面板。添加(两个);
添加标签面板(三个);
//labelPanel.SetBeOrder(新线条边框(颜色为黑色,1));
labelPanel.Set不透明(假);
JButton button0=createButton();
JButton button1=createButton();
JButton button2=createButton();
JButton button3=createButton();
setLayout(新的GridLayout(0,4,4,4));
按钮面板。添加(按钮0);
按钮面板。添加(按钮1);
按钮面板。添加(按钮2);
按钮面板。添加(按钮3);
//buttonPanel.setOrder(新行边框(颜色为黑色,1));
buttonPanel.set不透明(假);
label.setLayout(新的BorderLayout());
添加(labelPanel,BorderLayout.NORTH);
标签。添加(按钮面板,边框布局。南);
维度d=Toolkit.getDefaultToolkit().getScreenSize();
标签。设置首选尺寸(新尺寸(d.宽度/3,d.高度/3));
添加(标签、边框布局、中心);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
包装();
setVisible(真);
startBackground();
第二语言();
新线程(this.start();
printWords();//在EDT期间生成冻结Swing GUI
}
私有JButton createButton(){
JButton button=新JButton();
按钮。已涂漆(假);
按钮。设置订单(空);
按钮。设置可聚焦(假);
按钮设置边距(新插图(0,0,0,0)
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListsner() {
    private Iterator<Word> it = words.iterator();
    @Override 
    public void actionPerformed(ActionEvent e) {
        if (it.hasNext()) {
            label.setText(it.next().getName());
        }
        else {
            timer.stop();
        }
    }
};
timer.addActionListener(listener);
timer.start();
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.*;
//http://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java
public class ButtonsIcon extends JFrame implements Runnable {

    private static final long serialVersionUID = 1L;
    private Queue<Icon> iconQueue = new LinkedList<Icon>();
    private JLabel label = new JLabel();
    private Random random = new Random();
    private JPanel buttonPanel = new JPanel();
    private JPanel labelPanel = new JPanel();
    private Timer backTtimer;
    private Timer labelTimer;
    private JLabel one = new JLabel("one");
    private JLabel two = new JLabel("two");
    private JLabel three = new JLabel("three");
    private final String[] petStrings = {"Bird", "Cat", "Dog",
        "Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
    private boolean runProcess = true;
    private int index = 1;
    private int index1 = 1;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ButtonsIcon t = new ButtonsIcon();
            }
        });
    }

    public ButtonsIcon() {
        iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));

        one.setFont(new Font("Dialog", Font.BOLD, 24));
        one.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        two.setFont(new Font("Dialog", Font.BOLD, 24));
        two.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        three.setFont(new Font("Dialog", Font.BOLD, 10));
        three.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelPanel.setLayout(new GridLayout(0, 3, 4, 4));

        labelPanel.add(one);
        labelPanel.add(two);
        labelPanel.add(three);
        //labelPanel.setBorder(new LineBorder(Color.black, 1));
        labelPanel.setOpaque(false);

        JButton button0 = createButton();
        JButton button1 = createButton();
        JButton button2 = createButton();
        JButton button3 = createButton();

        buttonPanel.setLayout(new GridLayout(0, 4, 4, 4));
        buttonPanel.add(button0);
        buttonPanel.add(button1);
        buttonPanel.add(button2);
        buttonPanel.add(button3);
        //buttonPanel.setBorder(new LineBorder(Color.black, 1));
        buttonPanel.setOpaque(false);

        label.setLayout(new BorderLayout());
        label.add(labelPanel, BorderLayout.NORTH);
        label.add(buttonPanel, BorderLayout.SOUTH);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));

        add(label, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
        startBackground();
        startLabel2();
        new Thread(this).start();
        printWords(); // generating freeze Swing GUI durring EDT
    }

    private JButton createButton() {
        JButton button = new JButton();
        button.setBorderPainted(false);
        button.setBorder(null);
        button.setFocusable(false);
        button.setMargin(new Insets(0, 0, 0, 0));
        button.setContentAreaFilled(false);
        button.setIcon(nextIcon());
        button.setRolloverIcon(nextIcon());
        button.setPressedIcon(nextIcon());
        button.setDisabledIcon(nextIcon());
        nextIcon();
        return button;
    }

    private Icon nextIcon() {
        Icon icon = iconQueue.peek();
        iconQueue.add(iconQueue.remove());
        return icon;
    }

    // Update background at 4/3 Hz
    private void startBackground() {
        backTtimer = new javax.swing.Timer(750, updateBackground());
        backTtimer.start();
        backTtimer.setRepeats(true);
    }

    private Action updateBackground() {
        return new AbstractAction("Background action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setIcon(new ImageIcon(getImage()));
            }
        };
    }

    // Update Label two at 2 Hz
    private void startLabel2() {
        labelTimer = new javax.swing.Timer(500, updateLabel2());
        labelTimer.start();
        labelTimer.setRepeats(true);
    }

    private Action updateLabel2() {
        return new AbstractAction("Label action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                two.setText(petStrings[index]);
                index = (index + 1) % petStrings.length;
            }
        };
    }

    // Update lable one at 3 Hz
    @Override
    public void run() {
        while (runProcess) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    one.setText(petStrings[index1]);
                    index1 = (index1 + 1) % petStrings.length;
                }
            });
            try {
                Thread.sleep(300);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // Note: blocks EDT
    private void printWords() {
        for (int i = 0; i < petStrings.length; i++) {
            String word = petStrings[i].toString();
            System.out.println(word);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            three.setText(word);
        }
        three.setText("<html> Concurency Issues in Swing<br>"
                + " never to use Thread.sleep(int) <br>"
                + " durring EDT, simple to freeze GUI </html>");
    }

    public BufferedImage getImage() {
        int w = label.getWidth();
        int h = label.getHeight();
        GradientPaint gp = new GradientPaint(0f, 0f, new Color(
                127 + random.nextInt(128),
                127 + random.nextInt(128),
                127 + random.nextInt(128)),
                w, w,
                new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        g2d.setColor(Color.BLACK);
        return bi;
    }
}
    import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.*;


class TimeThis extends JFrame {

    private static final long serialVersionUID = 1L;
    private ArrayList<Word> words;
    private JTextField _textField;  // set by timer listener

    public TimeThis() throws IOException {

        _textField = new JTextField(5);
        _textField.setEditable(false);
        _textField.setFont(new Font("sansserif", Font.PLAIN, 30));

        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());
        content.add(_textField); 

        this.setContentPane(content);
        this.setTitle("Swing Timer");
        this.pack();
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        _textField.setText("loading...");

        readFile(); // read file
        printWords(); // print results
    }

    public void readFile(){

        try {
            BufferedReader in = new BufferedReader(new FileReader("adameve.txt"));
            words = new ArrayList<Word>();
            int lineNum = 1; // we read first line in start

            // delimeters of line in this example only "space"
            char [] parse = {' '};
            String delims = new String(parse);

            String line = in.readLine();
            String [] lineWords = line.split(delims);

            // split the words and create word object
            //System.out.println(lineWords.length);

            for (int i = 0; i < lineWords.length; i++) {
                Word w = new Word(lineWords[i]); 
                words.add(w);                                      
            }
            lineNum++;    // pass the next line

            line = in.readLine();

            in.close();

        } catch (IOException e) {
        }
    }
    private void printWords() {
            final Timer timer = new Timer(100, null);

            ActionListener listener = new ActionListener() {
                private Iterator<Word> w = words.iterator();
                @Override 
                public void actionPerformed(ActionEvent e) {
                    if (w.hasNext()) {
                        _textField.setText(w.next().getName());
                        //Prints to Console just Fine...
                        //System.out.println(w.next().getName());   
                    }
                    else {
                        timer.stop();
                    }
                }
            };
            timer.addActionListener(listener);
            timer.start();

    }
    class Word{
        private String name;

        public Word(String name) {
            this.name = name;
        }
        public String getName() {
            return name;
        }    
    }   

    public static void main(String[] args) throws IOException {
        JFrame ani = new TimeThis();
        ani.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ani.setVisible(true); 

    }
}