我想閃爍的JButton的背景顏色,但只有'睡眠'它的工作。如何閃爍任何JComponent的背景顏色?
我的代碼:
@Override
public void actionPerformed(ActionEvent e){
if(!empty){
}else{
myButton.setBackground(Color.RED);
try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e2){}
myButton.setBackground(Color.LIGHT_GRAY);
try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e1) {}
myButton.setBackground(Color.RED);
try {TimeUnit.MILLISECONDS.sleep(200);} catch (InterruptedException e1) {}
myButton.setBackground(Color.LIGHT_GRAY);
}
}
}
編輯: 不能發佈整個代碼,那麼多行。 該按鈕是一個的GridBagLayout內:
myButton= new Jbutton("Button!");
myButton.setBackground(Color.White);
myButton.setHorizontalAlignment(JTextField.CENTER);;
myButton.setForeground(Color.black);
GridBagConstraints gbc_myButton = new GridBagConstraints();
gbc_myButton.fill = GridBagConstraints.BOTH;
gbc_myButton.gridx = 0;
gbc_myButton.gridy = 1;
gbc_myButton.gridwidth=3;
panel.add(myButton, gbc_myButton);
編輯2: 我剛找出它不設置在運行時任何顏色(具有或不具有任何延遲/睡眠)。
你是什麼意思「只有'sleep'工作」? – ItamarG3
延時工作,但顏色不變。 – tomyforever
a)200毫秒很短,請嘗試更長的睡眠時間。 b)你在循環該代碼嗎? – ItamarG3