溫馨提示×

java定時器如何實現文字內容交換

小億
99
2024-06-12 09:18:33
欄目: 編程語言

在Java中實現文字內容交換可以使用定時器和定時任務來實現。以下是一個簡單的示例代碼:

import java.util.Timer;
import java.util.TimerTask;

public class TextSwitcher {

    private String text1 = "Hello";
    private String text2 = "World";
    private String currentText = text1;

    public void startTextSwitching() {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (currentText.equals(text1)) {
                    currentText = text2;
                } else {
                    currentText = text1;
                }
                System.out.println(currentText);
            }
        };
        timer.scheduleAtFixedRate(task, 0, 1000); // 切換文字每隔1秒
    }

    public static void main(String[] args) {
        TextSwitcher textSwitcher = new TextSwitcher();
        textSwitcher.startTextSwitching();
    }
}

在這個示例中,我們創建了一個TextSwitcher類,其中包含兩個文字內容text1text2,并定義了一個定時器任務來切換當前顯示的文字內容。定時器每隔1秒調用一次任務,根據當前顯示的文字內容來切換到另一個文字內容,并輸出到控制臺上。你可以根據自己的需求對定時器的時間間隔進行調整。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女