如何实现JDatePicker的FocusListener?

时间:2015-06-01 07:18:13

标签: java swing jdatechooser focuslistener

我想在FocusEvent的{​​{1}}中执行某些功能。我使用下面的代码来实现JDatePicker

FocusListener

此代码无效。这段代码中有错误吗?

1 个答案:

答案 0 :(得分:1)

由于个人原因,我不是JDatePicker的忠实粉丝。

您可以实现自己的版本,为您提供之后的功能,或者您可以尝试使用SwingLabs,{SwingX JXDatePicker,例如

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdesktop.swingx.JXDatePicker;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            add(new JButton("Before"));
            JXDatePicker picker = new JXDatePicker();
            picker.getEditor().addFocusListener(new FocusAdapter() {
                @Override
                public void focusGained(FocusEvent e) {
                    System.out.println("You have foucs");
                }
            });
            add(picker);
            add(new JButton("After"));
        }

    }
}