問題描述
當(dāng) jSpinner 值改變時(shí)如何立即更新.
How to make the update immediately when the jSpinner value was changed.
ChangeListener listener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
jLabel.setText(e.getSource());
}
};
spinner1.addChangeListener(listener);
上面的代碼不會(huì)自動(dòng)改變標(biāo)簽文本,它需要你在任何地方再次點(diǎn)擊才能更新.
The code above doesnt change the label text automatically, it required you to click again anyplace to update.
推薦答案
答案是配置JFormattedTextField中使用的格式化程序,它是微調(diào)器的編輯器的子項(xiàng):
The answer is to configure the formatter used in the JFormattedTextField which is a child of the spinner's editor:
formatter.setCommitsOnValidEdit(true);
不幸的是,得到一個(gè)人的手就像介紹句一樣又長(zhǎng)又臟:
Unfortunately, getting one's hand on it is as long and dirty as the introductory sentence:
final JSpinner spinner = new JSpinner();
JComponent comp = spinner.getEditor();
JFormattedTextField field = (JFormattedTextField) comp.getComponent(0);
DefaultFormatter formatter = (DefaultFormatter) field.getFormatter();
formatter.setCommitsOnValidEdit(true);
spinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
LOG.info("value changed: " + spinner.getValue());
}
});
一種稍微(但不是很多)更簡(jiǎn)潔的方法可能是繼承 NumberEditor 并公開一個(gè)允許配置的方法
A slightly (but not by much) cleaner way might be to subclass NumberEditor and expose a method which allows the config
這篇關(guān)于JSpinner 值變化事件的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!