开发者

Which button of JSpinner has been pressed?

Is it possible to know , from inside a ChangeL开发者_StackOverflow中文版istener receiving a ChangeEvent from a JSpinner, which button (increment/decrement) has been pressed?


Short answer : No there's no way to know which button was pressed

Long answer : depending on your model and your change listener, if you do a comparison between the new value and the previous value, it is possible to know if the user went forward or backward.


You can inspect the object firing the event. Perhaps save the value prior to the event and determine whether it went up or down during the event.


Compare the actual value to the previous one. Here is how:

ChangeEvent ce = ...
((JSpinner)ce.getSource()).getPreviousValue();


You can check the new value against the old value by storing the old value:

int currentValue = spinner.getValue();
spinner.addChangeListener(new javax.swing.event.ChangeListener() {
    public void stateChanged(javax.swing.event.ChangeEvent e) {
        int value = spinner.getValue();
        if(value > currentValue) {
            // up was pressed
        } else if(value < currentValue) {
            // down was pressed
        }
        currentValue = value;
    }
});


JSpinner is a composite component, it's possible to add mouseListeners to the components it contains. You'd have to experiment a bit to work out how to distinguish the buttons from one another and from the text field. One quick and dirty way would be to check their coordinates.

I'm not sure if you want to iterate over the components contained by the JSpinner itself, or those contained by the container returned by JSpinner.getEditor(), so try both.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜