![](/img/trans.png)
[英]How to change the background color of a JSpinner dependent on the current edited content of the field?
[英]How to change the background color of a JSpinner (Number model)?
我想將我的JSpinner
的背景顏色更改為紅色以通知用戶錯誤。 我的微調器使用數字 model(不知道它是否有影響)。 我嘗試了很多解決方案,但沒有一個有效。
jspinner.setBackground(Color.red);
jspinner.getEditor().getComponent(0).setBackground(Color.red);
我知道我必須訪問微調器的特定組件(如JFormattedTextField
)但我不知道該怎么做......)
這應該有效:
JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor)
spinner.getEditor(); jsEditor.getTextField().setBackground(Color.red);
但事實並非如此。 有人知道為什么嗎?
這是更改jSpinner背景顏色的最簡單方法:
SpinnerNumberModel nummodel = new SpinnerNumberModel(5, 0, 10, 1);
JSpinner numspinner = new JSpinner(nummodel);
numspinner.getEditor().getComponent(0).setBackground(Color.green);
//getComponent(0) gives you text field
JComponent editor = spinner.getEditor();
int n = editor.getComponentCount();
for (int i=0; i<n; i++)
{
Component c = editor.getComponent(i);
if (c instanceof JTextField)
{
c.setForeground(Color.red);
c.setBackground(Color.red);
}
}
確保你使 JTextField 不透明:
((JTextField)(connectTimeoutSpn.getEditor().getComponent(0))).setOpaque(true);
connectTimeoutSpn.getEditor().getComponent(0).setBackground(Color.green);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.