Swinghacks――动感JList(二)
public static final int ANIMATION_DURATION = 500;
public static final int ANIMATION_REFRESH = 50;
public AnimatedJList() {
super();
addListSelectionListener (this);
setCellRenderer (new AnimatedCellRenderer());
}
public void valueChanged (ListSelectionEvent lse) {
if (! lse.getValueIsAdjusting()) {
HashSet selections = new HashSet();
// System.out.println ("got last lse");
for (int i=0; i < getModel().getSize(); i++) {
if (getSelectionModel().isSelectedIndex(i))
selections.add (new Integer(i));
}
CellAnimator animator = new CellAnimator (selections.toArray());
animator.start();
}
}
public static void main (String[] args) {
JList list = new AnimatedJList ();
DefaultListModel defModel = new DefaultListModel();
list.setModel (defModel);
String[] listItems = {
"Chris", "Joshua", "Daniel", "Michael",
"Don", "Kimi", "Kelly", "Keagan"
};
Iterator it = Arrays.asList(listItems).iterator();
while (it.hasNext())
defModel.addElement (it.next());
// show list
JScrollPane scroller =
new JScrollPane (list,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
JFrame frame = new JFrame ("Checkbox JList");
frame.getContentPane().add (scroller);
frame.pack();
frame.setVisible(true);
}
class CellAnimator extends Thread {
Object[] selections;
long startTime;
long stopTime;
public CellAnimator (Object[] s) {
selections = s;
}
public void run() {
startTime = System.currentTimeMillis();
stopTime = startTime + ANIMATION_DURATION;
while (System.currentTimeMillis() < stopTime) {
colorizeSelections();
repaint();
try { Thread.sleep (ANIMATION_REFRESH); }
catch (InterruptedException ie) {}
}
// one more, at 100% selected color
colorizeSelections();
repaint();
}
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]));
}
colorizedSelectionForeground =
new Color (colorizedForeComps[0],
colorizedForeComps[1],
colorizedForeComps[2]);
colorizedSel