如何显示在图像的中心动态文本的JPanel
问题描述:
我有一个Java摆动计划,我想插入此图片:如何显示在图像的中心动态文本的JPanel
在市中心,这种形象的,我想插入一个动态文本是这样的:
05:00(这是一个定时器)
所以我建立这个代码:
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
现在我该如何插入这个标签在我的图像的中心,并将它放在我的JPanel?
答
将外部图像包裹在JLabel
中,对其应用BorderLayout
或GridBagLayout
,添加您的计时器标签。此外,您通过从EDT上下文之外更新组件的状态来违反Swing的线程规则。
更多细节
见 Concurrency in Swing相反,你可以考虑使用一个Swing取决于你希望什么Timer
或SwingWorker
实现
更多细节
见How to use Swing Timers和Worker Threads and SwingWorker“现在哪能插入这个标签在我的图像的中心,并把它放在我的JPanel ???“:JPanel在哪里? – gpasch