Java Swing鼠标监听器无法正常工作

时间:2013-04-21 19:26:14

标签: java swing swingx

我需要在SwingX JXDatePicker组件上激活MouseListener,这使我能够在用户单击组件时执行特定操作。 不幸的是,事件永远不会被触发。

这里有一小段代码可以重现问题:

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) {}
}

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时,控制台上没有单行输出。

任何帮助/提示都将不胜感激! 托马斯

1 个答案:

答案 0 :(得分:3)

要向MouseListener编辑器组件添加JXDatePicker's,请使用:

dp.getEditor().addMouseListener(this);

更新的 要向组件的打开ActionListener添加JButton,您可以使用:

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