View Javadoc
1   /*
2   Copyright 2011, Aiki IT, FotoRenamer
3   Licensed under the Apache License, Version 2.0 (the "License");
4   you may not use this file except in compliance with the License.
5   You may obtain a copy of the License at
6   
7       http://www.apache.org/licenses/LICENSE-2.0
8   
9   Unless required by applicable law or agreed to in writing, software
10  distributed under the License is distributed on an "AS IS" BASIS,
11  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  See the License for the specific language governing permissions and
13  limitations under the License.
14  */
15  package de.aikiit.fotorenamer.util;
16  
17  import lombok.AccessLevel;
18  import lombok.NoArgsConstructor;
19  import org.apache.logging.log4j.Logger;
20  import org.apache.logging.log4j.LogManager;
21  
22  import javax.swing.ImageIcon;
23  import java.awt.Component;
24  import java.awt.Dimension;
25  import java.awt.Toolkit;
26  
27  /**
28   * Helper class to center Swing-components.
29   *
30   * @author hirsch, 20.10.2003
31   * @version 2003-10-22
32   */
33  @NoArgsConstructor(access = AccessLevel.PRIVATE)
34  public final class ComponentGaugeUtil {
35      /**
36       * Logger for this class.
37       */
38      private static final Logger LOG =
39              LogManager.getLogger(ComponentGaugeUtil.class);
40  
41      /**
42       * Gauge the given component on screen.
43       *
44       * @param component Swing-component to gauge.
45       */
46      public static void makeCentered(final Component component) {
47          Toolkit toolkit = Toolkit.getDefaultToolkit();
48          Dimension dim = toolkit.getScreenSize();
49          int screenWidth = dim.width;
50          int screenHeight = dim.height;
51          component.setLocation((screenWidth - component.getSize().width) / 2,
52                  (screenHeight - component.getSize().height) / 2);
53      }
54  
55      /**
56       * Helper that transforms a given path into an ImageIcon. In case of errors
57       * <code>null</code> is returned.
58       *
59       * @param path File path that is to be converted into an icon.
60       * @return ImageIcon, located at the given path.
61       */
62      public static ImageIcon createImageIcon(final String path) {
63          assert path != null : "Path for image icon needs to be set.";
64          LOG.debug("Creating image icon from path " + path);
65          java.net.URL imgURL = ComponentGaugeUtil.class.getResource(path);
66          LOG.debug("extracted URL is: " + imgURL);
67  
68          if (imgURL != null) {
69              return new ImageIcon(imgURL);
70          } else {
71              LOG.error("Could not generate a valid URL from the given path: "
72                      + path);
73              return null;
74          }
75      }
76  }