只要循环正在运行,我就想每秒更新 Jlabel 文本。我怎么能这样做?我想这样做 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 的单线程性质排除了使用循环或Thread.sleep
您似乎正在尝试的方式。这样做只会阻塞 UI 并阻止它被绘制/更新,直到循环完成。
因为 Swing 不是线程安全的,所以你不能简单地使用另一种Thread
和上述方法来更新 UI,而不需要跳过一些障碍
您问题的锥形答案是使用 Swing Timer
,它会定期触发更新。因为这些更新是在事件调度线程的上下文中触发的,所以在您想要更新 UI 时可以安全地使用。
仔细查看如何使用 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);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句