有什么办法在他们之间用一封信一封又一封地表示“欢迎!”这个短语吗?我会提供我尝试过的东西,但我甚至没有接近于勉强工作,没有什么值得一提的。我想我得用一个包含扫描器的循环,对吗?任何帮助,谢谢:)
发布于 2013-09-17 02:09:01
警告
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();
}
}
}有关更多细节,请查看在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>);别担心,秋千会搞定的.
https://stackoverflow.com/questions/18840120
复制相似问题