gpt4 book ai didi

java - 简单Java : How to make string replace and wait then replace again?

转载 作者:行者123 更新时间:2023-12-02 04:38:47 25 4
gpt4 key购买 nike

我正在做一些东西,Applet 上将会有一个关于 Java 的“计算”页面!所以我想要它做的是首先拉绳并显示“正在计算”。然后一秒钟后它会替换该字符串并显示“正在计算...”,然后再次将该字符串替换为“正在计算...”并循环大约 5 次。有什么简单的方法可以做到这一点吗?

我想让它显示在小程序上!

最佳答案

您想要使用 Swing TimerSwingWorker。请参阅How to use Swing TimersWorker Threads and SwingWorker了解更多详情。

例如...

Calc

  import java.awt.Dimension;
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 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 static class TestPane extends JPanel {

private JLabel label;
private static final String DOTS = "...";
private static final String TEXT = "Calculating";
private int counter;

public TestPane() {
setLayout(new GridBagLayout());
label = new JLabel(getText());
add(label);

Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
if (counter > 3) {
counter = 0;
}
label.setText(getText());
}
});
timer.start();
}

protected String getText() {

String sufix = DOTS.substring(0, counter);
sufix = String.format("%-3s", sufix);

return TEXT + sufix;

}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

}

}

将其添加到小程序与添加到 JFrame 一样简单

关于java - 简单Java : How to make string replace and wait then replace again?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430761/

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