我有一个JButton
,当按下它时,它会将背景颜色从活动状态更改为正常状态:
final Color activeButtonColor = new Color(159, 188, 191);
final Color normalButtonColor = new Color(47, 55, 56);
当特定任务完成执行后,我想将活动按钮的颜色变回普通按钮的颜色。我正在使用
SwingWorker
,想知道是否有人可以建议一种有效的方法来执行此操作?button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
new SwingWorker<Object, Object>() {
protected Object doInBackground() throws Exception {
button.setBackground(activeButtonColor);
for (int note = 60; note < 120; note++) {
midiController.sendMidiMessage(1, note, 83);
midiController.stopMidiMessage(note, 83);
}
Thread.sleep(200);
return null;
}
protected void done() {
try {
Object result = get();
// Fade back
} catch (Exception ex) {
ex.printStackTrace();
if (ex instanceof java.lang.InterruptedException)
return;
}
}
}.execute();
}
});
编辑:为了清楚起见,我正在寻找一种有效的方法来将
activeButtonColor
的RGB值渐变回normalButtonColor
,而不必创建大量的Color
对象。可能吗?还是我只需要限制淡变步骤的数量以提高效率? 最佳答案
创建一个使用3个参数,一个按钮,一个from color和to color的方法。在该方法内部,创建一个可在背景中运行的Swingworker,以使颜色褪色。
然后,在您执行操作的动作监听器上,在执行任何操作之前,请从主动到正常调用淡入淡出方法。完成后,从正常到活动调用淡入淡出方法。
在这种情况下,您最终将使用3个挥杆工人。一个用于您的工作,一个用于第一次淡入淡出,一个用于最后淡入淡出。