[英]setting a timer for a label in Java
目前,我正在開發ATM模擬,主要有三個功能,即“顯示余額”,“取款”和“存款”。 由於這只是一個模擬,所以沒有自動提款機,由於這個原因,當客戶希望將錢存入帳戶時,我分配了一個隨機數。
關於我的問題,當用戶單擊存款時,該屏幕上會出現一個標簽。 我希望該標簽寫2秒鍾的“數錢”,然后顯示實際生成的金額。
我的問題是第一部分。 如何讓標簽寫2秒鍾的“計數”?
感謝您的答復和時間。
假設您已經創建了一個選擇的窗格(JPanel,JDesktopPane等),並為要顯示“ Counting Money”的“ Deposit”按鈕和“ JLabel”標簽創建了類似的JButton,則需要創建一個Thread
將與程序中的其他代碼並行運行,這樣您的程序就不必等待計數過程,直到您可以執行其他操作為止。 因此,您將創建一個Thread
對象,如下所示,並使用代碼Calendar.getInstance().getTimeInMillis()
獲取當前時間,並設置一個long
變量來保存開始時間。 然后使用while
循環,您將繼續檢查開始時間和當前時間之間的時差,以查看是否經過了2秒。 將此差異保存在循環內的另一個long
變量中,並讓循環檢查其值是否超過2000毫秒(2秒)。 當時間超過2秒時,while循環停止, Thread
可以繼續執行下一行代碼,這會將您的標簽設置為空(您可以將文本更改為所需的內容)。 此后, Thread
停止。 您的代碼應如下所示:
JLabel lblCount = new JLabel("");
lblCount.setBounds(92, 28, 243, 90);
windowPane.add(lblClock);
JButton btnDeposit = new JButton("Deposit Money");
btnDeposit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblCount.setText("Counting Money.....Please Wait");
long start = Calendar.getInstance().getTimeInMillis();
Thread timer = new Thread(){
public void run()
{
long time = Long.valueOf(0);
while(time < Long.valueOf(2))
{
time = (Calendar.getInstance().getTimeInMillis() - start)/1000;
}
lblCount.setText("");
}
};
}
});
btnDeposit.setBounds(78, 175, 118, 53);
windowPane.add(btnDeposit);
public void crono() {
TimerTask tarea = new TimerTask() {
@Override
public void run() {
int ok = 0;
if (actualTime < maxTime * 1000) {
ok = 1;
//because its in miliseconds
actualTime = actualTime + 1000;
}
switch (ok) {
case 1:
int displayTime= actualTime/ 1000;
label.setText(Integer.toString(displayTime));
break;
//if actual is over maxtime
case 0:
label.setText("TIME IS UP");
break;
default:
break;
}
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(tarea, 0, 1000);
//the first argument will be the task, the second the starting time, and the final one is //the period, in this case it will be one second
}
嘗試使用線程。
Thread t;
t = new Thread(){
@Override
public void run(){
label.setText("counting...");
Thread.sleep(2000);//Time in Milliseconds
label.setText("Display what you want.");
}
}
t.start();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.