Swinghacks――动感JList(一)

2014-11-24 11:47:15 · 作者: · 浏览: 29
ok,我承认动感这个词用的有点过,还是先上图看效果
解释一下,图片中是没有什么动感的,其实效果是这样
当选中item时,蓝色的选中背景会从白色渐变到蓝色,给人动感~
虽然这种动感没有特别实际的用处,不过实现原理还是有点意思,来看看
1、先通过lookandfeel获取选中和未选中的背景颜色,在转换成rgb浮点数组float[3]
[java] www.2cto.com
UIDefaults uid = UIManager.getLookAndFeel().getDefaults();
Color listForeground = uid.getColor ("List.foreground");
float[] foregroundComps = listForeground.getRGBColorComponents(null);
2、在valueChanged方法中,启动thread做背景渐变效果;通过计时,每50ms进行一次repaint,总共执行500ms
[java]
public void run() {
startTime = System.currentTimeMillis();
stopTime = startTime + ANIMATION_DURATION;
while (System.currentTimeMillis() < stopTime) {
colorizeSelections();
repaint();
//每间隔ANIMATION_REFRESH时间就repaint一次
try { Thread.sleep (ANIMATION_REFRESH); }
catch (InterruptedException ie) {}
}
// one more, at 100% selected color
colorizeSelections();
repaint();
}
3、repaint之前调用colorizeSelections方法设置背景前景颜色,而colorizeSelections方法是根据时间来计算背景显示的百分比
这个计算其实就是把背景的rgb值取百分比
[java]
public void colorizeSelections() {
// calculate % completion relative to start/stop times
float elapsed = (float) (System.currentTimeMillis() - startTime);
float completeness = Math.min ((elapsed/ANIMATION_DURATION), 1.0f);
// System.out.println ("completeness = " + completeness);
// calculate scaled color
float colorizedForeComps[] = new float[3];
float colorizedBackComps[] = new float[3];
for (int i=0; i<3; i++) {
colorizedForeComps[i] =
foregroundComps[i] +
(completeness *
(foregroundSelectionComps[i] - foregroundComps[i]));
colorizedBackComps[i] =
backgroundComps[i] +
(completeness *
(backgroundSelectionComps[i] - backgroundComps[i]));
}
这样repaint之前就设置好了背景色,不断repaint的话就产生动感渐变的效果了
上代码:
[java]
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class AnimatedJList extends JList
implements ListSelectionListener {
static java.util.Random rand = new java.util.Random();
static Color listForeground, listBackground,
listSelectionForeground, listSelectionBackground;
static float[] foregroundComps, backgroundComps,
foregroundSelectionComps, backgroundSelectionComps;
static {
UIDefaults uid = UIManager.getLookAndFeel().getDefaults();
listForeground = uid.getColor ("List.foreground");
listBackground = uid.getColor ("List.background");
listSelectionForeground = uid.getColor ("List.selectionForeground");
listSelectionBackground = uid.getColor ("List.selectionBackground");
foregroundComps =
listForeground.getRGBColorComponents(null);
foregroundSelectionComps =
listSelectionForeground.getRGBColorComponents(null);
backgroundComps =
listBackground.getRGBColorComponents(null);
backgroundSelectionComps =
listSelectionBackground.getRGBColorComponents(null);
}
public Color colorizedSelectionForeground,
colorizedSelectionBackground;