Add a cell renderer on the eye color JList view component that display the color...
[Persons_Comparator.git] / src / EyeView.java
index aa54c8b8d76bdf0109e9fc294d8a21d63feacf63..99b5d0b680847537199c0747262398175aa553c4 100644 (file)
@@ -1,28 +1,28 @@
 import javax.swing.*;
+import java.awt.*;
+import java.util.Arrays;
 
-public class EyeView extends JComponent {
+public class EyeView extends JPanel {
     private Eye eyeObj;
     private JLabel label;
     private JList colorsList;
 
-    EyeView() {
-        setEyeObj(new Eye());
+    /**
+     * @param eyeObj
+     */
+    EyeView(Eye eyeObj) {
+        setEyeObj(eyeObj);
         this.label = new JLabel();
         this.label.setText("Eyes color");
-        this.colorsList = new JList(getEyeObj().getColorsList());
+        this.colorsList = new JList<>(this.getEyeObj().getColorsList());
         this.colorsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         this.colorsList.setLayoutOrientation(JList.VERTICAL);
+        this.colorsList.setSelectedIndex(Arrays.asList(this.getEyeObj().getColorsList()).indexOf(this.getEyeObj().getStrColor()));
+        this.colorsList.setCellRenderer(new EyeCellRenderer());
         add(label);
         add(colorsList);
     }
 
-    /**
-     * @param eyeObj
-     */
-    EyeView(Eye eyeObj) {
-        setEyeObj(eyeObj);
-    }
-
     /**
      * @return
      */
@@ -36,4 +36,21 @@ public class EyeView extends JComponent {
     public void setEyeObj(Eye eyeObj) {
         this.eyeObj = eyeObj;
     }
+
+    public JList getColorsList() {
+        return colorsList;
+    }
+
+    private static class EyeCellRenderer extends DefaultListCellRenderer {
+        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
+            Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
+            Eye currentEye = new Eye((String) list.getModel().getElementAt(index));
+            c.setBackground(currentEye.getColor());
+            c.setForeground(Color.WHITE);
+            if (isSelected) {
+                setBackground(getBackground().darker());
+            }
+            return c;
+        }
+    }
 }