Search code examples
javaimageswingjlabelthread-sleep

Java - How to display JLabel text update every X seconds while another action is in place


Sorry if the code isnt neat. But I am a messy code writer O-O anyway. I need to know why when I do this the JLabel text does not pop up. And how can I make the text pop you.

Frame.java

package rpg.tec;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Frame extends JFrame {

    private static final long serialVersionUID = 1L;
    //Speed of car
    int speed = 3;        
    ImageIcon image = new ImageIcon("C:\\Users\\elliotbewey\\Desktop\\DarkArcaneIMGS\\download.png");
    JLabel location = new JLabel("Hello");
    JLabel imageLabel = new JLabel(image); 

    public void run() {       
        setLayout(null);
        imageLabel.setBounds(10, 10, 400, 400);
        imageLabel.setVisible(true);
        imageLabel.setLayout(null);
        location.setVisible(true);
        location.setText("Hello");
        add(imageLabel);
        add(location);        
        int loc = 1;        
        for(int i = 0; i< 500; i++) {           
            try {
                //sending the actual Thread of execution to sleep X milliseconds
                Thread.sleep(50);
            } catch(InterruptedException ie) {}            
            loc = loc + speed;            
            imageLabel.setLocation(loc, 0);
            location.setLocation(2, 10);
            add(location);
        }
    }

    void messy() {          
    }
}

Main.java

package rpg.main;

import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import rpg.tec.Frame;

public class Main {

    public static void main(String[] args) {
        Frame frame = new Frame();
        String Version = "0.0.1";
        frame.setTitle(Version);
        frame.setVisible(true);
        frame.setSize(600, 450);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.run();
    }
}

No errors occur

What happens as a result is no errors. Just no text appearing we have a moving car across the screen but no text. How do I fix this? How do I make the text appear (JLabel) hello?


Solution

  • First of all, why do you have:

    location.setLocation(2, 10);
    add(location);
    

    inside your for loop? No values are changing. (Unless you're still working on it)

    Second of all, you need to setBounds for the JLabel as well for it to appear. I just put:

    location.setBounds(100,100,100,100);
    

    and it appears.

    If you change the

    location.setLocation(2, 10);
    

    in the first part to

    location.setLocation(loc, 10);
    

    the JLabel will move.