如何连续将 jlabel 从一个文本更改为另一个文本,然后反复返回相同的文本

How to continuously change a jlabel from one text to another and then back to the same text repeatedly

我有这个程序,假设 JLabel 将其文本更改为 "Welcome",然后更改为 "Register",然后返回到“Welcome

计划:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ItemListener;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.geom.*;
import java.util.*;
public class optionsDineIn extends JPanel {
   JLabel lab1 = new JLabel("Welcome");
   JPanel p = new JPanel();

    public void construct() {
 if(lab1.getText().equals("Welcome")) {
        new java.util.Timer().schedule( 
            new java.util.TimerTask() {
                @Override
                public void run() {
                    //for(int i=0; i<=100; i++){
                    lab1.setText("Register");
                    //}
                }
            }, 
            2000 
        );
    }

            p.add(lab1);
   }

您可以尝试使用重复任务:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ItemListener;
import javax.imageio.ImageIO;
import java.awt.Graphics;
import java.awt.geom.*;
import java.util.*;
public class optionsDineIn extends JPanel {
   JLabel lab1 = new JLabel("Welcome");
   boolean lab1state = false;
   JPanel p = new JPanel();

    public void construct() {
        new java.util.Timer().schedule( 
            new java.util.TimerTask() {
                @Override
                public void run() {
                    if(lab1state){
                        lab1.setText("Welcome");
                    }else{
                        lab1.setText("Register");
                    }
                    lab1state = !lab1state;
                }
            }, 
            2000,
            2000
        );
    }
    p.add(lab1);
   }