Cleanup (avoid unneeded NPE)
[idea/community.git] / platform / platform-impl / src / com / intellij / ide / plugins / RatesPanel.java
1 /*
2  * Copyright 2000-2014 JetBrains s.r.o.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.intellij.ide.plugins;
17
18 import com.intellij.icons.AllIcons;
19 import com.intellij.openapi.util.IconLoader;
20
21 import javax.swing.*;
22 import java.awt.*;
23
24 /**
25 * @author Konstantin Bulenkov
26 */
27 public class RatesPanel extends JPanel {
28   public static int MAX_RATE = 5;
29
30   private static final Icon STAR = AllIcons.Ide.Rating;
31
32   private static final Icon STAR3 = AllIcons.Ide.Rating1;
33   private static final Icon STAR4 = AllIcons.Ide.Rating2;
34   private static final Icon STAR5 = AllIcons.Ide.Rating3;
35   private static final Icon STAR6 = AllIcons.Ide.Rating4;
36   private static final Icon[] STARs = new Icon[]{IconLoader.getDisabledIcon(STAR), STAR3, STAR3, STAR4, STAR4, STAR5, STAR5, STAR6, STAR6, STAR};
37
38   private JLabel[] myLabels = new JLabel[MAX_RATE];
39
40   public RatesPanel() {
41     super(new GridBagLayout());
42     setOpaque(false);
43     GridBagConstraints gc =
44       new GridBagConstraints(GridBagConstraints.RELATIVE, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE,
45                              new Insets(0, 0, 0, 0), 0, 0);
46     for (int i = 0, myLabelsLength = myLabels.length; i < myLabelsLength; i++) {
47       myLabels[i] = new JLabel();
48       myLabels[i].setOpaque(false);
49       add(myLabels[i], gc);
50     }
51   }
52
53   public void setRate(String rating) {
54     Double dblRating = 0d;
55     if (rating != null) {
56       try {
57         dblRating = Double.valueOf(rating);
58       }
59       catch (NumberFormatException ignore) { }
60     }
61
62     final int intRating = dblRating.intValue();
63
64     for (int i = 0; i < intRating; i++) {
65       myLabels[i].setIcon(STAR);
66     }
67
68     if (intRating < MAX_RATE) {
69       myLabels[intRating].setIcon(STARs[((Double)(dblRating * 10)).intValue() % 10]);
70       for (int i = 1 + intRating; i < MAX_RATE; i++) {
71         myLabels[i].setIcon(IconLoader.getDisabledIcon(STAR));
72       }
73     }
74   }
75
76   @Override
77   public Dimension getPreferredSize() {
78     return new Dimension(55, 11);
79   }
80 }