我有一個JSpinner
使用SpinnerNumberModel
使用double
值的GUI。如何根據當前編輯的字段內容更改JSpinner的背景顏色?
只要我改變JSpinner
的Editor
的內容,我希望背景更改爲黃色(表明當前顯示的值不是「保存」分別在JSpinner
之一的Model
。
如果該內容無效(如出由指定的允許範圍內的我SpinnerNumberModel
或文本爲「ABC」)的背景應更改爲紅色。
我想實現我想用一個FocusListener
既可但還沒有成功,我也不確定它是否可以工作,因爲我需要檢查聚焦和散焦之間的內容。
我選中了所有Listeners
的教程,其中存在Swing
組件,但無法找到適合該作業的正確組件。 (here I informed myself)
我是新來的Listeners
概念,真的希望這讓我更接近解決問題,還有助於任何幫助一般理解Listeners
以及如何在這種情況下更好地使用它們!
我很基本的代碼與使用的焦點偵聽器所提到的可憐嘗試例如:
public class test implements FocusListener{
JFrame frame;
SpinnerNumberModel model;
JSpinner spinner;
JComponent comp;
JFormattedTextField field;
public test() {
JFrame frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
model = new SpinnerNumberModel(0., 0., 100., 0.1);
spinner = new JSpinner(model);
comp = spinner.getEditor();
field = (JFormattedTextField) comp.getComponent(0);
field.addFocusListener(this);
frame.getContentPane().add(spinner);
frame.getContentPane().add(new JButton("defocus spinner")); //to have something to defocus when testing :)
frame.pack();
frame.setVisible(true);
}
@Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
//when the values of the field and the spinner don't match, the field should get yellow
if(!field.getValue().equals(spinner.getModel().getValue())) {
field.setBackground(Color.YELLOW);
}
}
@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
//if they match again, reset to white
if(!field.getValue().equals(spinner.getModel().getValue())) {
field.setBackground(Color.RED);
}
}
}
1)爲了更好地幫助越早,張貼[MCVE]或[簡要,獨立的,正確的示例](http://www.sscce.org/)。 2)請參閱[檢測/修復代碼塊的懸掛緊密支架](http://meta.stackexchange.com/q/251795/155831),以解決問題,我不再擔心修復問題。 3)爲什麼不改變微調框的邊框顏色,或者它旁邊圖標的顏色?我總是小心地改變使用顏色出於各自原因的組件的BG顏色。 –
感謝fb,我會盡快爲自己找到一個解決方案來修復代碼示例,並且已經修復了懸掛支架! 這樣的東西肯定會讓你這樣的經驗豐富的用戶感到厭煩,但對於像我這樣的新手來說肯定是個大陷阱;) – Vito