简体   繁体   English

通过Java Swing中的循环更新Jlabel文本?

[英]Updating the Jlabel text by a loop in java Swing?

I want to update the Jlabel text in every second as long as the loop is running. 只要循环正在运行,我想每秒更新一次Jlabel文本。 how could I do this? 我该怎么办? I want to do as this fromat. 我想这样做。

JPanel jpnl=new JPanel();
    jfrm.add(jpnl);
    String[] fonts=GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
    jlab = new JLabel("This is Label");
    jpnl.add(jlab);

        for(int i=0;i<fonts.length;i++){
            System.out.println(fonts[i]);
            jlab.setText(fonts[i]);
            jlab.setFont(new Font(fonts[i],Font.PLAIN,30));
            jlab.setForeground(Color.DARK_GRAY);
        }

Swing's single threaded nature precludes using a loop or Thread.sleep in the way you seem to be trying. Swing的单线程性质避免以您似乎尝试的方式使用循环或Thread.sleep Doing so, will simply block the UI and prevent it from been painted/updated until the loop is completed. 这样做只会阻塞UI并阻止其绘制/更新,直到循环完成为止。

Because Swing is not thread safe, you can't simply use another Thread and the above approaches to update the UI, without jumping through some hoops 由于Swing并不是线程安全的,因此您不能简单地使用另一个Thread和上述方法来更新UI,而无需跳过一些麻烦。

The conical answer to your question is to use a Swing Timer , which triggers an update at a regular bases. 您问题的圆锥形答案是使用Swing Timer ,它会定期触发更新。 Because these updates are triggered within the context of the Event Dispatching Thread, it makes it safe to use when you want to update the UI. 由于这些更新是在事件调度线程的上下文中触发的,因此当您要更新UI时,可以安全地使用它。

Take a closer look at How to use Swing Timers for more details 详细了解如何使用Swing计时器

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private String[] fonts;
        private final JLabel jlab;
        private int index = 0;

        public TestPane() {
            setLayout(new GridBagLayout());
            fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
            jlab = new JLabel("This is Label");
            add(jlab);

            Timer timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    updateFont();
                    index++;
                    if (index >= fonts.length) {
                        ((Timer)e.getSource()).stop();
                    }
                }
            });
            timer.setInitialDelay(0);
            timer.start();
        }

        protected void updateFont() {
            System.out.println(fonts[index]);
            jlab.setText(fonts[index]);
            jlab.setFont(new Font(fonts[index], Font.PLAIN, 30));
            jlab.setForeground(Color.DARK_GRAY);           
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM