Java是一款流行的編程語(yǔ)言,它可以使用按鍵和倒計(jì)時(shí)進(jìn)行綁定。
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.JLabel; public class CountdownTimer implements KeyListener { private JFrame frame; private JLabel countdownLabel; public CountdownTimer() { frame = new JFrame("倒計(jì)時(shí)器"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); countdownLabel = new JLabel("10", JLabel.CENTER); frame.add(countdownLabel); frame.addKeyListener(this); frame.setSize(300, 200); frame.setVisible(true); } public static void main(String[] args) { new CountdownTimer(); } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_SPACE) { int secondsRemaining = Integer.parseInt(countdownLabel.getText()); secondsRemaining--; if (secondsRemaining >= 0) { countdownLabel.setText("" + secondsRemaining); } else { frame.dispose(); } } } @Override public void keyReleased(KeyEvent e) {} @Override public void keyTyped(KeyEvent e) {} }
以上代碼實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的倒計(jì)時(shí)器。在窗口中顯示一個(gè)標(biāo)簽,標(biāo)簽中顯示10。當(dāng)用戶按下空格鍵時(shí),倒計(jì)時(shí)開(kāi)始并且每按一次空格鍵,倒計(jì)時(shí)減一秒。當(dāng)?shù)褂?jì)時(shí)結(jié)束時(shí),窗口關(guān)閉。
上一篇css3 打勾效果