Search code examples
javabluej

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


I have this program, Where the JLabel is suppose to change its text to "Welcome" and then to "Register" and then back to "Welcome

Program:

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);
   }

Solution

  • You can try using a repeating task:

    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);
       }