gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:52:04 26 4
gpt4 key购买 nike

只要循环运行,我想每秒更新一次 Jlabel 文本。我怎么能这样做?我想这样做。

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 的单线程性质排除了以您似乎正在尝试的方式使用循环或 Thread.sleep。这样做只会阻塞 UI 并防止它被绘制/更新,直到循环完成。

因为 Swing 不是线程安全的,您不能简单地使用另一个 Thread 和上述方法来更新 UI,而不跳过一些环节

您问题的圆锥形答案是使用 Swing Timer,它会定期触发更新。因为这些更新是在事件调度线程的上下文中触发的,所以当您想要更新 UI 时可以安全地使用它。

仔细看看How to use Swing Timers了解更多详情

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

}

}

关于java - 通过 java Swing 中的循环更新 Jlabel 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44671147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com