Sfoglia il codice sorgente

Adds new helper function to enable loading files from Jars & JVM

Default Image, if loading failed
Andreas T. Meyer-Berg 5 anni fa
parent
commit
f9836b594f

+ 43 - 5
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/MainFrame.java

@@ -1,11 +1,11 @@
 package de.tu_darmstadt.tk.SmartHomeNetworkSim.view;
 
+import java.awt.Color;
 import java.awt.Dimension;
 import java.awt.Toolkit;
 import java.awt.event.WindowEvent;
 import java.awt.event.WindowStateListener;
-import java.io.File;
-import java.io.IOException;
+import java.awt.image.BufferedImage;
 
 import javax.imageio.ImageIO;
 import javax.swing.JFrame;
@@ -13,6 +13,8 @@ import javax.swing.JMenuBar;
 import javax.swing.JMenuItem;
 
 import java.awt.BorderLayout;
+import java.io.File;
+import java.io.InputStream;
 
 import javax.swing.SwingConstants;
 
@@ -64,9 +66,11 @@ public class MainFrame extends JFrame {
 		try {
 			/**
 			 * Icon of the MainFrame UI
-			 */
-			this.setIconImage(ImageIO.read(new File("src/main/ressources/images/SmartHomeNetworkSim_icon.jpeg")));
-		} catch (IOException e) {
+			 */	
+			String path = "images/SmartHomeNetworkSim_icon.jpeg";
+			//this.setIconImage(ImageIO.read(new File("src/main/resources/images/SmartHomeNetworkSim_icon.jpeg")));
+			this.setIconImage(loadFile(path));
+		} catch (Exception e) {
 			System.err.println("WARNING: Failed to load Icon image in MainFrame.java");
 			e.printStackTrace();
 		}
@@ -95,4 +99,38 @@ public class MainFrame extends JFrame {
 			}
 		});
 	}
+	
+	/**
+	 * Loads resource image from the given path (resources/path).
+	 * Return default image, if loading failed
+	 * @param path pathe where the image is located
+	 * @return Image from path
+	 */
+	public BufferedImage loadFile(String path){
+		try {
+			//Try loading Image from jar/resources
+			InputStream i = this.getClass().getClassLoader().getResourceAsStream(path);
+			return ImageIO.read(i);
+		} catch (Exception e) {
+			//Try loading from absolute path, if it failed (e.g. starting the program from eclipse or jvm) 
+			//extend path with path to resources
+			path = "src/main/resources/"+ path;
+			try {
+				return ImageIO.read(new File(path));
+			} catch (Exception e2) {
+				/**
+				 * return default Image (red cross on white background)
+				 */
+				BufferedImage def = new BufferedImage(64, 64, BufferedImage.TYPE_INT_RGB);
+				for(int i = 0; i<64; i++)
+					for(int j = 0; j<64; j++){
+						if(i*(64-i)-j*(64-j)==0)
+							def.setRGB(i, j, Color.RED.getRGB());
+						else
+							def.setRGB(i, j, Color.white.getRGB());
+					}
+				return def;
+			}
+		}
+	}
 }