有没有办法逐个字母地显示短语“欢迎!”,并且它们之间的延迟很小?我会提供我尝试过的东西,但我什至还没有接近勉强工作,没有什么值得一提的。我想我必须使用包含扫描仪的循环,是吗?感谢任何帮助,谢谢:)
最佳答案
注意事项
Swing 是一个单线程框架,也就是说,对 UI 的所有更新和修改都应该在事件调度线程的上下文中执行。
同样,任何阻止 EDT 的操作都会阻止它处理(除其他外)、绘制更新,这意味着在删除阻止之前,UI 不会更新。
示例
有几种方法可以实现这一目标。您可以使用 SwingWorker
虽然这将是一个很好的学习练习,但对于这个问题来说可能有点过头了。
相反,您可以使用 javax.swing.Timer
。这允许您定期安排回调,这些回调在 EDT 的上下文中执行,这将允许您安全地更新 UI。
import java.awt.BorderLayout;
import java.awt.EventQueue;
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 AnimatedLabel {
public static void main(String[] args) {
new AnimatedLabel();
}
public AnimatedLabel() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(100, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private String text = "Hello";
private JLabel label;
private int charIndex = 0;
public TestPane() {
setLayout(new GridBagLayout());
label = new JLabel();
add(label);
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String labelText = label.getText();
labelText += text.charAt(charIndex);
label.setText(labelText);
charIndex++;
if (charIndex >= text.length()) {
((Timer)e.getSource()).stop();
}
}
});
timer.start();
}
}
}
看看Concurrency in Swing了解更多详情
评论更新
主要问题是你的text
值包含在 <html>
中
static String text = "<html>Welcome! I will ask simple, two-answer questions, and you will answer them. Simple as that. </html>";
然后将其应用到您的标签...
final JLabel centerText = new JLabel(text);
因此,当计时器运行时,它最终会再次附加文本......
"<html>Welcome! I will ask simple, two-answer questions, and you will answer them. Simple as that. </html><html>Welcome! I will ask simple, two-answer questions, and you will answer them. Simple as that. </html>"
这是无效的,因为 </html>
之后的所有内容将被忽略。
相反,删除 <html>
来自 text
的标签
static String text = "Welcome! I will ask simple, two-answer questions, and you will answer them. Simple as that.";
并设置标签的初始文本 <html>
final JLabel centerText = new JLabel("<html>);
别担心,Swing 会解决这个问题...
关于java - 在 JLabel 中逐字母显示字符串 "animation"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18840120/