熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

小技巧:Java Swing中使用雙擊事件

2022-06-13   來源: Java核心技術 

  直接在JBuilder中新建一個應用程序至於具體步驟就不描述了此代碼沒有main函數無法直接運行下面我貼出在Frame中的代碼
  
    import javaawt*;
    import javaawtevent*;
    import javaxswing*;
    import comborlandjbcllayout*;
    import javautilDate;
    public class Frame
    extends JFrame {
    JPanel contentPane;
    BorderLayout borderLayout = new BorderLayout();
    JPanel jPanel = new JPanel();
    XYLayout xYLayout = new XYLayout();
    JScrollPane jScrollPane = new JScrollPane();
    JList jList = new JList();
    //初始化的JList中的數據
    String[] strData = {
    One Tow Three};
    //保存點擊按鈕的時間
    long clickTime = ;
  
    //Construct the frame
    public Frame() {
    enableEvents(AWTEventWINDOW_EVENT_MASK);
    try {
    jbInit();
    }
    catch (Exception e) {
    eprintStackTrace();
    }
    }
  
    //Component initialization
    private void jbInit() throws Exception {
    contentPane = (JPanel)thisgetContentPane();
    contentPanesetLayout(borderLayout);
    thissetSize(new Dimension( ));
    thissetTitle(Frame Title);
  
    jPanelsetLayout(xYLayout);
    jListaddMouseListener(new Frame_jList_mouseAdapter(this));
    contentPaneadd(jPanel BorderLayoutCENTER);
    jPaneladd(jScrollPane new XYConstraints( ));
    jScrollPanegetViewport()add(jList null);
    jListsetListData(strData);
    }
  
    //Overridden so we can exit when window is closed
    protected void processWindowEvent(WindowEvent e) {
    superprocessWindowEvent(e);
    if (egetID() == WindowEventWINDOW_CLOSING) {
    Systemexit();
    }
    }
    //具體實現按鈕雙擊的功能的方法 很簡單的算法不做解釋了
    public boolean checkClickTime() {
    long nowTime = (new Date())getTime();
  
    if ( (nowTime clickTime) < ) {
    clickTime = nowTime;
    return true;
    }
    clickTime = nowTime;
    return false;
  
    }
  
    void jList_mouseReleased(MouseEvent e) {
    //判斷是否雙擊是的話寫你要實現的功能
    if (checkClickTime()) {
    Systemoutprintln(Click Double);
  
    }
    }
    }
  
    class Frame_jList_mouseAdapter
    extends javaawteventMouseAdapter {
    Frame adaptee;
  
    Frame_jList_mouseAdapter(Frame adaptee) {
    thisadaptee = adaptee;
    }
  
    public void mouseReleased(MouseEvent e) {
    adapteejList_mouseReleased(e);
    }
    }
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25810.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.