简体   繁体   English

如何在Image的中心将动态文本显示到JPanel中

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

I have a Java swing Program and I want insert this image: 我有一个Java swing程序,我想插入此图像:

在此处输入图片说明

At the center, of this image, I want to insert a dynamic text like this: 在此图像的中心,我想插入一个动态文本,如下所示:

05:00 (this is a timer) 05:00(这是一个计时器)

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??? 现在如何在我的图像中心插入这个标签,并在我的JPanel上显示它?

Wrap the outer image in a JLabel , apply a BorderLayout or GridBagLayout to it, add your timer label to it. 将外部图像包装在JLabel ,对其应用BorderLayoutGridBagLayout ,并为其添加计时器标签。 Also, you're violating the thread rules of Swing by updating the state of the component from outside the context of the EDT. 另外,通过从EDT上下文外部更新组件的状态来违反Swing的线程规则。

See Concurrency in Swing for more details 有关更多详细信息,请参见Swing中的并发。

Instead, you might consider using a Swing Timer or SwingWorker depending on what you hope to achieve 相反,您可以根据希望实现的目标考虑使用Swing TimerSwingWorker

See How to use Swing Timers and Worker Threads and SwingWorker for more details 有关更多详细信息,请参见如何使用Swing计时器工作线程以及SwingWorker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM