如何使用for循环在JLabel中显示更改文本

问题描述 投票:0回答:1
public class UserInterface {
    OpenFile of = new OpenFile();

    JFrame jf = new JFrame("File Manager");
    JButton jb1 = new JButton("Open File");
    JLabel jl1 = new JLabel("Recommendations appear here");
    JLabel jl2 = new JLabel();
    JList<String> list;

    public void build() {

        DefaultListModel<String> str = new DefaultListModel<String>();

        for (int i = 0; i < of.f.length; i++) {
            str.addElement(of.f[i].getAbsolutePath());
        }

        list = new JList<String>(str);

        Border b = BorderFactory.createLineBorder(Color.black, 2);
        Font f = new Font("Arial", Font.BOLD, 20);

        jb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                of.OpenFileMethod(list.getSelectedValue());
            }
        });

        jl1.setFont(f);
        jl1.setBorder(b);
        list.setFont(f);
        jf.add(jl1).setBounds(30, 100, 300, 200);
        jf.add(list).setBounds(400, 100, 300, 300);
        jf.add(jb1).setBounds(250, 300, 100, 50);
        jf.setLayout(null);
        jf.setSize(800, 800);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        for (int i = 0; i < 100; i++) {
            jl1.setText("Loading.");
            jl1.setText("Loading...");
        }
    }
}

for循环中的问题,只将最后一个“loading ...”文本设置为JLabel我希望它进入循环并打印100次。可能是在启动swing应用程序之前循环结束。对此有何解决方案?

java swing jlabel
1个回答
2
投票

对此有何解决方案?

他们没有错,这段代码完美无缺,但这里的问题是当循环执行它时,眨眼之间就完成了!

这个案子你最好的朋友是班级javax.swing.Timer

并且该示例将向您展示如何使用它并希望解决您的问题,计时器拥有自己的共享Thread,因此您不必担心它将在不挂起您的ui或阻止您的代码的情况下运行。

//this int determines the time delay for each time it executes it's actions
    private int delay = 20;
    private int times = 0;
    private String text = "Loading ";
    private Timer textTimer;
    private class TimerAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            times++;
            String theSetText = text;
            for (int i = 0; i < times; i++) {
                theSetText += ".";
            }
            if (times == 3) {
                times = 0;
            }
        }

    }

你总是可以通过timer.addActioListener方法添加更多动作监听器,它也将在那里循环。

对于您的问题,只需将上面的代码添加到您的类中,并添加替换代码中的循环

textTimer = new Timer (delay,new TimerAction ());
textTimer.start();

并且当时间合适时(如你所愿)当你想要停止只是打电话时

textTimer.stop();

停止计时器运行这是一个链接,可以获得更多关于How to Use Swing Timers主题的信息

© www.soinside.com 2019 - 2024. All rights reserved.