简体   繁体   English

按下了JSpinner的哪个按钮?

[英]Which button of JSpinner has been pressed?

是否可以从从JSpinner接收ChangeEvent的ChangeListener内部知道按下了哪个按钮(增加/减少)?

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. JSpinner是一个复合组件,可以将mouseListeners添加到它包含的组件中。 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. 我不确定您是否要遍历JSpinner本身包含的组件,或JSpinner.getEditor()返回的容器所包含的组件,因此请尝试两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM