01 /*
02 * Copyright 2014-2017 the original author or authors.
03 *
04 * Licensed under the Apache License, Version 2.0 (the "License");
05 * you may not use this file except in compliance with the License.
06 * You may obtain a copy of the License at
07 *
08 * http://www.apache.org/licenses/LICENSE-2.0
09 *
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 griffon.javafx.support.crystalicons;
17
18 import griffon.plugins.crystalicons.Crystal;
19 import javafx.scene.image.Image;
20
21 import javax.annotation.Nonnull;
22 import java.net.URL;
23
24 import static griffon.plugins.crystalicons.Crystal.invalidDescription;
25 import static griffon.util.GriffonNameUtils.requireNonBlank;
26 import static java.util.Objects.requireNonNull;
27
28 /**
29 * @author Andres Almiray
30 */
31 public class CrystalIcon extends Image {
32 private static final String ERROR_CRYSTAL_NULL = "Argument 'crystal' must not be null.";
33 private Crystal crystal;
34 private int size;
35
36 public CrystalIcon(@Nonnull Crystal crystal) {
37 this(crystal, 16);
38 }
39
40 public CrystalIcon(@Nonnull Crystal crystal, int size) {
41 super(toURL(crystal, size), true);
42 this.crystal = requireNonNull(crystal, ERROR_CRYSTAL_NULL);
43 this.size = size;
44 }
45
46 public CrystalIcon(@Nonnull String description) {
47 super(toURL(description));
48 this.crystal = Crystal.findByDescription(description);
49
50 String[] parts = description.split(":");
51 if (parts.length == 3) {
52 try {
53 size = Integer.parseInt(parts[2]);
54 } catch (NumberFormatException e) {
55 throw invalidDescription(description, e);
56 }
57 } else if (size == 0) {
58 size = 16;
59 }
60 }
61
62 @Nonnull
63 private static String toURL(@Nonnull Crystal crystal, int size) {
64 requireNonNull(crystal, ERROR_CRYSTAL_NULL);
65 String resource = crystal.asResource(size);
66 URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
67 if (url == null) {
68 throw new IllegalArgumentException("Icon " + crystal.formatted() + ":" + size + " does not exist");
69 }
70 return url.toExternalForm();
71 }
72
73 @Nonnull
74 private static String toURL(@Nonnull String description) {
75 requireNonBlank(description, "Argument 'description' must not be blank");
76 String resource = Crystal.asResource(description);
77 URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
78 if (url == null) {
79 throw new IllegalArgumentException("Icon " + description + " does not exist");
80 }
81 return url.toExternalForm();
82 }
83
84 @Nonnull
85 public Crystal getCrystal() {
86 return crystal;
87 }
88
89 public int getSize() {
90 return size;
91 }
92 }
|