Java代码实现时钟
生活随笔
收集整理的這篇文章主要介紹了
Java代码实现时钟
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
實現效果如圖:
Java代碼:
文件一:ClockPanel.java
文件二:ClockFrame.java
import java.awt.*; import java.awt.event.*; import javax.swing.*;/*** @author 張振坤*/ @SuppressWarnings("serial") public class ClockFrame extends JDialog {private float opqua = 0.7f;private ClockPanel clockPanel;private Point fp; // 拖曳窗體之前的鼠標位置public static void main(String args[]) {EventQueue.invokeLater(new Runnable() {public void run() {try {ClockFrame frame = new ClockFrame();// 創建窗體對象frame.setVisible(true);// 顯示窗體} catch (Exception e) {e.printStackTrace();}}});}/*** 布局窗體的構造方法*/public ClockFrame() {super();setUndecorated(true);// 取消窗體修飾setAlwaysOnTop(true);// 窗體置頂setTitle("石英鐘");// 設置窗體標題getContentPane().setLayout(new BorderLayout());setBounds(100, 30, 217, 257);setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);clockPanel = new ClockPanel();// 創建時鐘面板getContentPane().add(clockPanel);// 為時鐘面板添加鼠標按鍵事件監聽器clockPanel.addMouseListener(new MouseAdapter() {public void mousePressed(final MouseEvent e) {fp = e.getPoint();if (e.getButton()==MouseEvent.BUTTON3){System.exit(0);// 右鍵退出}}});// 在時鐘面板的鼠標拖曳事件中移動窗體clockPanel.addMouseMotionListener(new MouseMotionAdapter() {public void mouseDragged(final MouseEvent e) {JDialog frame = (JDialog) getRootPane().getParent();Point point = e.getLocationOnScreen();frame.setLocation(point.x - fp.x, point.y - fp.y);}});pack();addKeyListener(new KeyAdapter() {// 為窗體添加鍵盤事件監聽器public void keyPressed(final KeyEvent e) {int code = e.getKeyCode();switch (code) {// 判斷按鍵編碼case KeyEvent.VK_ADD:// +符號按鍵會降低透明圖opqua += 0.05;opqua = opqua > 0.95f ? 1f : opqua;break;case KeyEvent.VK_SUBTRACT:// -符號按鍵會提升透明度opqua -= 0.05;opqua = opqua < 0.1f ? 0.1f : opqua;break;}// 如果按Ctrl+Shift+X組合鍵,將退出程序if (code == KeyEvent.VK_X&& e.getModifiersEx() == (KeyEvent.CTRL_DOWN_MASK | KeyEvent.SHIFT_DOWN_MASK))System.exit(0);}});Dimension screenSize = getToolkit().getScreenSize();double width = screenSize.getWidth();int x = (int) (width - getWidth() - 30);setLocation(x, 30);new Thread() {// 創建線程對象,更新時鐘面板界面@Overridepublic void run() {try {while (true) {sleep(1000);// 休眠1秒clockPanel.repaint();// 重新繪制時鐘面板界面}} catch (InterruptedException e) {e.printStackTrace();}}}.start();} }兩個Java文件就實現了!!Java是不是很牛逼!!哈哈。接下來講解一下實現步驟:
歐克,這個實現功能就到此結束了。
總結
以上是生活随笔為你收集整理的Java代码实现时钟的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 以软件测试的角度测试一支笔,软件测试面试
- 下一篇: java美元兑换,(Java实现) 美元