简单的Java:如何进行字符串替换并等待再次替换?

时间:2015-05-25 03:20:23

标签: java string applet

我正在制作一些东西,在Applet上有一个关于Java的“计算”页面!所以我想要它做的是第一个抽绳并显示“计算”。然后在一秒钟后它替换该字符串并说“Calculating ...”然后再次用“Calculating ...”替换该字符串并循环约5次。有没有简单的方法呢?

我希望它在小程序上显示它!

1 个答案:

答案 0 :(得分:2)

您要么使用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);
      }

    }

  }

将此添加到applet就像添加到JFrame

一样简单