| 1 | import javax.swing.*; |
| 2 | import java.awt.*; |
| 3 | import java.util.Arrays; |
| 4 | |
| 5 | public class EyeView extends JPanel { |
| 6 | private Eye eyeObj; |
| 7 | private JLabel label; |
| 8 | private JList colorsList; |
| 9 | |
| 10 | /** |
| 11 | * @param eyeObj |
| 12 | */ |
| 13 | EyeView(Eye eyeObj) { |
| 14 | setEyeObj(eyeObj); |
| 15 | this.label = new JLabel(); |
| 16 | this.label.setText("Eyes color"); |
| 17 | this.colorsList = new JList<>(this.getEyeObj().getColorsList()); |
| 18 | this.colorsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); |
| 19 | this.colorsList.setLayoutOrientation(JList.VERTICAL); |
| 20 | this.colorsList.setSelectedIndex(Arrays.asList(this.getEyeObj().getColorsList()).indexOf(this.getEyeObj().getStrColor())); |
| 21 | this.colorsList.setCellRenderer(new EyeCellRenderer()); |
| 22 | add(label); |
| 23 | add(colorsList); |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * @return |
| 28 | */ |
| 29 | public Eye getEyeObj() { |
| 30 | return eyeObj; |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * @param eyeObj |
| 35 | */ |
| 36 | public void setEyeObj(Eye eyeObj) { |
| 37 | this.eyeObj = eyeObj; |
| 38 | } |
| 39 | |
| 40 | public JList getColorsList() { |
| 41 | return colorsList; |
| 42 | } |
| 43 | |
| 44 | private static class EyeCellRenderer extends DefaultListCellRenderer { |
| 45 | public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { |
| 46 | Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); |
| 47 | Eye currentEye = new Eye((String) list.getModel().getElementAt(index)); |
| 48 | c.setBackground(currentEye.getColor()); |
| 49 | c.setForeground(Color.WHITE); |
| 50 | if (isSelected) { |
| 51 | setBackground(getBackground().darker()); |
| 52 | } |
| 53 | return c; |
| 54 | } |
| 55 | } |
| 56 | } |