Swinghacks -- Dynamic JList

Source: Internet
Author: User
Tags getcolor

OK, I admit that the word "dynamic" is used a bit. Let's take a look at the effect and explain it first. There is nothing dynamic in the picture. In fact, the effect is that when the item is selected in this way, the selected blue background changes from white to blue ~ Although this kind of dynamic motion is not very practical, the implementation principle is a bit interesting. Let's take a look at 1. Get the selected and unselected background colors through lookandfeel first, in the float [3] [java] www.2cto. comUIDefaults uid = UIManager. getLookAndFeel (). getDefaults (); Color listForeground = uid. getColor ("List. foreground "); float [] foregroundComps = listForeground. getRGBColorComponents (null); 2. In the valueChanged method, start the thread to perform the background gradient effect; By timing, repaint is performed every 50 ms, and a total of 500 ms [java] public void run () is executed () {startTime = System. cur Required timemillis (); stopTime = startTime + ANIMATION_DURATION; while (System. currentTimeMillis () <stopTime) {colorizeSelections (); repaint (); // repaint once every interval of ANIMATION_REFRESH time try {Thread. sleep (ANIMATION_REFRESH);} catch (InterruptedException ie) {}}// one more, at 100% selected color colorizeSelections (); repaint ();} 3. Call the colorizeSelections method to set the background foreground color before repainting. The colorizeSelections method calculates the background color based on time. Display percentage this calculation is actually to take the rgb value of the background as the percentage [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 colorizedB AckComps [] = 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]);} the background color is set before repainting, continuously repainting produces a dynamic gradient effect. The code above: [java] import java. awt. *; import javax. swing. *; import javax. swing. even T. *; 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, sums, backgroundSelectionComps; static {UIDefaults uid = UIManager. getLookAndFe El (). 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 blocks, colorizedSelectionBackground; 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 (); Defau LtListModel 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, ScrollPaneConstan Ts. 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 comple Teness = 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] = background Comps [I] + (completeness * (backgroundSelectionComps [I]-backgroundComps [I]);} colorizedSelectionForeground = new Color (colorizedForeComps [0], colorizedForeComps [1], colorizedForeComps [2]); colorizedSelectionBackground = new Color (colorizedBackComps [0], colorizedBackComps [1], colorizedBackComps [2]); // System. out. println ("fore =" + colorizedSelectionForeground); // System. out. println ("back = "+ ColorizedSelectionBackground);} class AnimatedCellRenderer extends DefaultListCellRenderer {public Component extends (JList list, Object value, int index, boolean isSelected, boolean hasFocus) {Component returnMe = super. getListCellRendererComponent (list, value, index, isSelected, hasFocus); if (isSelected) {returnMe. setForeground (colorizedSelectionForeground); ret UrnMe. setBackground (colorizedSelectionBackground);/* this might be necessary if you have more elaborate cells if (returnMe instanceof Container) {Component [] children = (Container) returnMe ). getComponents (); System. out. println (children. length + "children"); for (int I = 0; (children! = Null) & (I <children. length); I ++) {children [I]. setForeground (colorizedSelectionForeground); children [I]. setBackground (colorizedSelectionBackground);} */if (returnMe instanceof JComponent) (JComponent) returnMe ). setOpaque (true) ;}return returnMe ;}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.