bircastri
bircastri

Reputation: 2159

How can display dynamic text at the center of Image into JPanel

I have a Java swing Program and I want insert this image:

enter image description here

At the center, of this image, I want to insert a dynamic text like this:

05:00 (this is a timer)

So I have build this code:

public void getLabel(){
    labelTempoGara = new TimeRefreshRace();
    labelTempoGara.setForeground(Color.white);
    labelTempoGara.start();
}
    class TimeRefreshRace extends JLabel implements Runnable {

        private boolean isAlive = false;

        public void start() {
            threadTempoCorsa = new Thread(this);
            isAlive = true;
            threadTempoCorsa.start();
        }

        public void run() {
            int tempoInSecondi = programma.getTempoGara() % 60;
            int minuti = programma.getTempoGara() / 60;
            while (isAlive) {
                try {
                    if (minuti <= 0 && tempoInSecondi<=1) {
                        isRun=false;
                        this.setText("00:00");
                        isAlive = false;
                        salvaDatiCorsa();
                        break;
                    }
                    if(tempoInSecondi<=1){
                        minuti--;
                        tempoInSecondi=60;
                    }
                    --tempoInSecondi;
                    this.setText(minuti+":"+ tempoInSecondi);
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    log.logStackTrace(e);
                }
            }
        }

        public void kill() {
            isAlive = false;
            isRun=false;
        }

    }//fine autoclass

Now how can I insert this label at the center of my Image and diplay it on my JPanel???

Upvotes: 0

Views: 85

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347234

Wrap the outer image in a JLabel, apply a BorderLayout or GridBagLayout to it, add your timer label to it. Also, you're violating the thread rules of Swing by updating the state of the component from outside the context of the EDT.

See Concurrency in Swing for more details

Instead, you might consider using a Swing Timer or SwingWorker depending on what you hope to achieve

See How to use Swing Timers and Worker Threads and SwingWorker for more details

Upvotes: 2

Related Questions