2013-04-21 68 views
0

我需要在SwingX JXDatePicker組件上具有活動的MouseListener,使我能夠在用戶單擊組件時執行特定操作。 不幸的是,事件從未被觸發。Java Swing鼠標偵聽器無法正常工作

由此一小塊的代碼能重現問題:

public class TestDummy4 extends JFrame implements MouseListener{ 

    private static final long serialVersionUID = -2424758762078571430L; 

    public TestDummy4(){ 
     super(); 
     this.getContentPane().setLayout(new BorderLayout()); 

     //Adds date picker 
     JXDatePicker dp = new JXDatePicker(); 
     dp.getEditor().setEditable(false); 
     dp.getEditor().setHighlighter(null); 
     dp.addMouseListener(this); 

     this.getContentPane().add(dp); 
     this.pack(); 
     this.setVisible(true); 
    } 

    public static void main(String[] args) throws IOException { 
     javax.swing.SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       //Builds GUI 
       new TestDummy4(); 
      } 
     }); 

    } 

    @Override 
    public void mouseClicked(MouseEvent e) { 
     System.out.println("Mouse clicked"); 
    } 

    @Override 
    public void mousePressed(MouseEvent e) { 
     System.out.println("Mouse pressed"); 
    } 
    @Override 
    public void mouseReleased(MouseEvent e) {} 
    @Override 
    public void mouseEntered(MouseEvent e) { 
     System.out.println("Mouse Entered"); 
    } 
    @Override 
    public void mouseExited(MouseEvent e) {} 
} 

有了這個代碼,我已經輸出的不是單行線在控制檯上的JXDatePicker點擊時。

任何幫助/提示將不勝感激! 托馬斯

+0

同樣的問題與所有複合組件(fi與核心組合,請參閱教程):您不能將低級偵聽器添加到父級和經驗ct它會得到事件通知給孩子 – kleopatra 2013-04-21 21:55:28

+0

*「Java Swing鼠標監聽器..」*小點,但MouseListener(像大多數監聽器)是純AWT。 – 2013-04-22 01:09:44

回答

3

添加MouseListenerJXDatePicker's編輯器組件使用:

dp.getEditor().addMouseListener(this); 

更新: 要將ActionListener添加到組件的開放JButton你可以使用:

JButton openButton = (JButton) dp.getComponent(1); 
openButton.addActionListener(myActionListener); 
+0

非常感謝swift回覆:單擊編輯器時確實有效,但不幸的是,它不會捕獲鼠標點擊旁邊的下拉箭頭(也是JXDatePicker組件的一部分)......任何建議?非常感謝 – Tom 2013-04-21 20:25:23

+0

查看更新..... – Reimeus 2013-04-21 20:42:46

+0

Thx,但不幸的是這不起作用。更具體地說:我正在尋找使用打開月視圖的箭頭(而不是月視圖本身)在組件上添加監聽器。還有其他建議嗎?非常感謝 – Tom 2013-04-21 20:47:51

相關問題