public About() { cl = ClassLoader.getSystemClassLoader(); // ----------------------------------------CENTER--------------------------------// imgAbout = new ImageIcon(cl.getResource("om.png")); lblAbout = new JLabel(imgAbout); lblAbout.setBounds(0, 0, 450, 263); JPanel pnlCenter = new JPanel(); pnlCenter.setLayout(null); pnlCenter.add(lblAbout); btnOk = new JButton(new ImageIcon(cl.getResource("ok.png"))); btnOk.setBounds(390, 215, 40, 30); pnlCenter.add(btnOk); btnOk.addActionListener(this); // -----------------------------------CONTAINER----------------------------------// Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(pnlCenter, BorderLayout.CENTER); setSize(450, 280); setVisible(true); setResizable(false); setLocation(580, 280); // setDefaultCloseOperation(EXIT_ON_CLOSE); }
public ViewportRenderer() { ClassLoader loader = getClass().getClassLoader(); surfaceIcon = new ImageIcon(loader.getResource(IMAGE_BASE + "/vrjuggler-surface-viewport.png")); simIcon = new ImageIcon(loader.getResource(IMAGE_BASE + "/vrjuggler-sim-viewport.png")); scaledSurfaceIcon = new ImageIcon(); scaledSimIcon = new ImageIcon(); }
public static Icon getIcon(String iconName) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource("test/check/icons/" + iconName + ".gif"); if (url != null) return new ImageIcon(url); url = cl.getResource("test/check/icons/" + iconName + ".png"); if (url != null) return new ImageIcon(url); return null; }
/** * Gets the URL of the icon file denoted by the specified file name. * * @param fileName The file name. May be {@code null}. * @return The URL of the specified file name, or {@code null} if {@code fileName} is {@code * null}, or {@code null} if there is not file with the specified file name in the bundle * class path. */ private static URL getIconURL(String fileName) { if (fileName == null) { return null; } ClassLoader loader = OWLIcons.class.getClassLoader(); URL url = loader.getResource(fileName); if (url == null && !isFileNameAbsolute(fileName)) { url = loader.getResource(ALTERNATIVE_ICONS_DIRECTORY + fileName); } return url; }
public void init() { vlog.debug("init called"); setBackground(Color.white); ClassLoader cl = this.getClass().getClassLoader(); ImageIcon icon = new ImageIcon(cl.getResource("com/tigervnc/vncviewer/tigervnc.png")); logo = icon.getImage(); }
/** @param frameName title name for frame */ public ShowSavedResults(String frameName) { super(frameName); aboutRes = new JTextArea( "Select a result set from" + "\nthose listed and details" + "\nof that analysis will be" + "\nshown here. Then you can" + "\neither delete or view those" + "\nresults using the buttons below."); aboutScroll = new JScrollPane(aboutRes); ss = new JScrollPane(sp); ss.getViewport().setBackground(Color.white); // resMenu.setLayout(new FlowLayout(FlowLayout.LEFT,10,1)); ClassLoader cl = getClass().getClassLoader(); rfii = new ImageIcon(cl.getResource("images/Refresh_button.gif")); // results status resButtonStatus = new JPanel(new BorderLayout()); Border loweredbevel = BorderFactory.createLoweredBevelBorder(); Border raisedbevel = BorderFactory.createRaisedBevelBorder(); Border compound = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel); statusField = new JTextField(); statusField.setBorder(compound); statusField.setEditable(false); }
@Nullable public static Icon findIcon(@NotNull String path, @NotNull ClassLoader classLoader) { path = undeprecate(path); if (isReflectivePath(path)) return getReflectiveIcon(path, classLoader); if (!StringUtil.startsWithChar(path, '/')) return null; final URL url = classLoader.getResource(path.substring(1)); return findIcon(url); }
/** * Load image with current class loader. * * @param fileName image resource file name * @return image */ public static Image loadSwtImage(String fileName) { Image result = null; try { ClassLoader classloader = DavGatewayTray.class.getClassLoader(); URL imageUrl = classloader.getResource(fileName); result = new Image(display, imageUrl.openStream()); } catch (IOException e) { DavGatewayTray.warn(new BundleMessage("LOG_UNABLE_TO_LOAD_IMAGE"), e); } return result; }
public NodeSettingsPanel() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } // Try to get icons for the toolbar buttons try { ClassLoader loader = getClass().getClassLoader(); mClusterIcon = new ImageIcon(loader.getResource(COMMON_IMG_ROOT + "/ClusterIcon.png")); mIconLabel.setIcon(mClusterIcon); } catch (Exception e) { // Ack! No icons. Use text labels instead mIconLabel.setText(""); } }
private MultiMap<String, ProjectTemplate> loadLocalTemplates() { ConcurrentMultiMap<String, ProjectTemplate> map = new ConcurrentMultiMap<String, ProjectTemplate>(); ProjectTemplateEP[] extensions = ProjectTemplateEP.EP_NAME.getExtensions(); for (ProjectTemplateEP ep : extensions) { ClassLoader classLoader = ep.getLoaderForClass(); URL url = classLoader.getResource(ep.templatePath); if (url != null) { LocalArchivedTemplate template = new LocalArchivedTemplate(url, classLoader); if (ep.category) { TemplateBasedCategory category = new TemplateBasedCategory(template, ep.projectType); myTemplatesMap.putValue(new TemplatesGroup(category), template); } else { map.putValue(ep.projectType, template); } } } return map; }
/** * Constructor del juego que inicializa los valores. * * @param juga * @param jugadorActual */ public Juego(ArrayList<Jugador> juga, Jugador jugadorActual) { jugadores = new ArrayList<>(); this.jugadores = juga; this.jugador = jugadorActual; loader = Juego.class.getClassLoader(); utilidades = new Util(); claseTime = new Time(); ventana = new JFrame("Concéntrese - Juan S."); ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ventana.setSize(520, 475); ventana.setLayout(null); ventana.setResizable(false); contadorJugadas = 0; cartaPorDefecto = new ImageIcon(loader.getResource("recursos/carta8.gif")); panel = new JPanel(); panel.setSize(300, 450); panel.setLayout(new GridLayout(4, 4)); intentos = new JLabel("Intento : 0"); etiquetaTiempoPartida = new JLabel("Tiempo: "); tiempoPartida = new JLabel("00.00.000"); etiquetaTiempoPartida.setFont(etiquetaTiempoPartida.getFont().deriveFont(20.0f)); tiempoPartida.setFont(tiempoPartida.getFont().deriveFont(20.0f)); intentos.setFont(intentos.getFont().deriveFont(20.0f)); intentos.setBounds(320, 50, 200, 30); tiempoPartida.setBounds(420, 5, 200, 30); etiquetaTiempoPartida.setBounds(320, 5, 200, 30); ventana.add(tiempoPartida); ventana.add(etiquetaTiempoPartida); ventana.add(intentos); ventana.add(panel); crearMenuSuperior(); crearMatrizIconos(); crearArrayBotones(); crearTemporizador(); ventana.setLocationRelativeTo(null); ventana.setVisible(true); }
/** Éste método crea una matriz con íconos y los asigna a cada botón. */ private void crearMatrizIconos() { ImageIcon[][] miMatrizIconos = new ImageIcon[4][4]; iconos = new ArrayList<>(); int indice = 0; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; j++) { if (indice >= nombreCartas.length) { indice = 0; } miMatrizIconos[i][j] = new ImageIcon(loader.getResource("recursos/" + nombreCartas[indice])); miMatrizIconos[i][j].setDescription( nombreCartas[ indice]); // set description sirve para dar al usuario una breve explicacion textual // de la imagen. iconos.add(miMatrizIconos[i][j]); ++indice; } } Collections.shuffle( iconos); // el metodo shuffle de la clase collections sirve para bajarar las cartas, es un // randomizador de arraylist. }
/** * QSAdminGUI - Control Panel for QuickServer Admin GUI - QSAdminGUI * * @author Akshathkumar Shetty * @since 1.3 */ public class QSAdminGUI extends JPanel /*JFrame*/ { private static Logger logger = Logger.getLogger(QSAdminGUI.class.getName()); private static QSAdminMain qsadminMain = null; private static String pluginDir = "./../plugin"; private ClassLoader classLoader = getClass().getClassLoader(); public ImageIcon logo = new ImageIcon(classLoader.getResource("icons/logo.gif")); public ImageIcon logoAbout = new ImageIcon(classLoader.getResource("icons/logo.png")); public ImageIcon ball = new ImageIcon(classLoader.getResource("icons/ball.gif")); private HeaderPanel headerPanel; private MainCommandPanel mainCommandPanel; private CmdConsole cmdConsole; private PropertiePanel propertiePanel; // private StatsPanel statsPanel; private JTabbedPane tabbedPane; private JFrame parentFrame; final HashMap pluginPanelMap = new HashMap(); // --v1.3.2 private ArrayList plugins = new ArrayList(); private JMenu mainMenu, helpMenu; private JMenuBar jMenuBar; private JMenuItem loginMenuItem, exitMenuItem, aboutMenuItem; /** Logs the interaction, Type can be S - Server Sent C - Client Sent */ public void logComand(String command, char type) { logger.info("For[" + type + "] " + command); } /** Displays the QSAdminGUi with in a JFrame. */ public static void showGUI(String args[], final SplashScreen splash) { java.awt.EventQueue.invokeLater( new Runnable() { public void run() { try { UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel"); } catch (Exception e) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ee) { } } qsadminMain = new QSAdminMain(); JFrame frame = new JFrame("QSAdmin GUI"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); QSAdminGUI qsAdminGUI = new QSAdminGUI(qsadminMain, frame); qsAdminGUI.updateConnectionStatus(false); frame.getContentPane().add(qsAdminGUI); frame.pack(); frame.setSize(700, 450); frame.setIconImage(qsAdminGUI.logo.getImage()); JFrameUtilities.centerWindow(frame); frame.setVisible(true); if (splash != null) splash.kill(); } }); } public QSAdminGUI(QSAdminMain qsadminMain, JFrame parentFrame) { this.parentFrame = parentFrame; Container cp = this; qsadminMain.setGUI(this); cp.setLayout(new BorderLayout(5, 5)); headerPanel = new HeaderPanel(qsadminMain, parentFrame); mainCommandPanel = new MainCommandPanel(qsadminMain); cmdConsole = new CmdConsole(qsadminMain); propertiePanel = new PropertiePanel(qsadminMain); if (headerPanel == null || mainCommandPanel == null || cmdConsole == null || propertiePanel == null) { throw new RuntimeException("Loading of one of gui component failed."); } headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); cp.add(headerPanel, BorderLayout.NORTH); JScrollPane propertieScrollPane = new JScrollPane(propertiePanel); // JScrollPane commandScrollPane = new JScrollPane(mainCommandPanel); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, mainCommandPanel, cmdConsole); splitPane.setOneTouchExpandable(false); splitPane.setDividerLocation(250); // splitPane.setDividerLocation(0.70); tabbedPane = new JTabbedPane(JTabbedPane.TOP); tabbedPane.addTab("Main", ball, splitPane, "Main Commands"); tabbedPane.addTab("Get/Set", ball, propertieScrollPane, "Properties Panel"); QSAdminPluginConfig qsAdminPluginConfig = null; PluginPanel pluginPanel = null; // -- start of loadPlugins try { File xmlFile = null; ClassLoader classLoader = null; Class mainClass = null; File file = new File(pluginDir); File dirs[] = null; if (file.canRead()) dirs = file.listFiles(new DirFileList()); for (int i = 0; dirs != null && i < dirs.length; i++) { xmlFile = new File(dirs[i].getAbsolutePath() + File.separator + "plugin.xml"); if (xmlFile.canRead()) { qsAdminPluginConfig = PluginConfigReader.read(xmlFile); if (qsAdminPluginConfig.getActive().equals("yes") && qsAdminPluginConfig.getType().equals("javax.swing.JPanel")) { classLoader = ClassUtil.getClassLoaderFromJars(dirs[i].getAbsolutePath()); mainClass = classLoader.loadClass(qsAdminPluginConfig.getMainClass()); logger.fine("Got PluginMainClass " + mainClass); pluginPanel = (PluginPanel) mainClass.newInstance(); if (JPanel.class.isInstance(pluginPanel) == true) { logger.info("Loading plugin : " + qsAdminPluginConfig.getName()); pluginPanelMap.put("" + (2 + i), pluginPanel); plugins.add(pluginPanel); tabbedPane.addTab( qsAdminPluginConfig.getName(), ball, (JPanel) pluginPanel, qsAdminPluginConfig.getDesc()); pluginPanel.setQSAdminMain(qsadminMain); pluginPanel.init(); } } else { logger.info( "Plugin " + dirs[i] + " is disabled so skipping " + qsAdminPluginConfig.getActive() + ":" + qsAdminPluginConfig.getType()); } } else { logger.info("No plugin configuration found in " + xmlFile + " so skipping"); } } } catch (Exception e) { logger.warning("Error loading plugin : " + e); logger.fine("StackTrace:\n" + MyString.getStackTrace(e)); } // -- end of loadPlugins tabbedPane.addChangeListener( new ChangeListener() { int selected = -1; int oldSelected = -1; public void stateChanged(ChangeEvent e) { // if plugin selected = tabbedPane.getSelectedIndex(); if (selected >= 2) { ((PluginPanel) pluginPanelMap.get("" + selected)).activated(); } if (oldSelected >= 2) { ((PluginPanel) pluginPanelMap.get("" + oldSelected)).deactivated(); } oldSelected = selected; } }); // tabbedPane.setBorder(BorderFactory.createEmptyBorder(0,5,5,5)); cp.add(tabbedPane, BorderLayout.CENTER); buildMenu(); } public void setStatus(String msg) { headerPanel.setStatus(msg); } public void setResponse(String res) { int msgType = JOptionPane.PLAIN_MESSAGE; if (res.startsWith("+OK")) msgType = JOptionPane.INFORMATION_MESSAGE; if (res.startsWith("-ERR")) msgType = JOptionPane.ERROR_MESSAGE; JOptionPane.showMessageDialog( QSAdminGUI.this, res.substring(res.indexOf(" ") + 1), "Response", msgType); } public void appendToConsole(String msg) { cmdConsole.append(msg); } public void setConsoleSend(boolean flag) { cmdConsole.setSendEdit(flag); } public void updateConnectionStatus(boolean connected) { if (connected == true) { headerPanel.setLogoutText(); loginMenuItem.setText("Logout"); } else { headerPanel.setLoginText(); loginMenuItem.setText("Login..."); } mainCommandPanel.updateConnectionStatus(connected); propertiePanel.updateConnectionStatus(connected); cmdConsole.updateConnectionStatus(connected); Iterator iterator = plugins.iterator(); PluginPanel updatePluginPanel = null; while (iterator.hasNext()) { updatePluginPanel = (PluginPanel) iterator.next(); updatePluginPanel.updateConnectionStatus(connected); } if (connected == true) { int selected = tabbedPane.getSelectedIndex(); if (selected >= 2) { ((PluginPanel) pluginPanelMap.get("" + selected)).activated(); } } } // --v1.3.2 public static void setPluginDir(String dir) { pluginDir = dir; } public static String getPluginDir() { return pluginDir; } private void buildMenu() { jMenuBar = new javax.swing.JMenuBar(); mainMenu = new javax.swing.JMenu(); mainMenu.setText("Main"); loginMenuItem = new JMenuItem("Login..."); loginMenuItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { headerPanel.handleLoginLogout(); } }); mainMenu.add(loginMenuItem); exitMenuItem = new JMenuItem("Exit"); exitMenuItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { if (qsadminMain.isConnected() == true) { headerPanel.handleLoginLogout(); } System.exit(0); } }); mainMenu.add(exitMenuItem); helpMenu = new javax.swing.JMenu(); helpMenu.setText("Help"); aboutMenuItem = new JMenuItem("About..."); aboutMenuItem.setEnabled(true); aboutMenuItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { about(); } }); helpMenu.add(aboutMenuItem); jMenuBar.add(mainMenu); jMenuBar.add(helpMenu); parentFrame.setJMenuBar(jMenuBar); } private void about() { JOptionPane.showMessageDialog( this, "QSAdminGUI\n\n" + "GUI Client for QSAdminServer of QuickServer.\n" + "This is compliant with QuickServer v" + QSAdminMain.VERSION_OF_SERVER + " release.\n\n" + "Copyright (C) QuickServer.org\n" + "http://www.quickserver.org", "About QSAdminGUI", JOptionPane.INFORMATION_MESSAGE, logoAbout); } }
public static boolean showLicensing() { if (Config.getLicenseResource() == null) return true; ClassLoader cl = Main.class.getClassLoader(); URL url = cl.getResource(Config.getLicenseResource()); if (url == null) return true; String license = null; try { URLConnection con = url.openConnection(); int size = con.getContentLength(); byte[] content = new byte[size]; InputStream in = new BufferedInputStream(con.getInputStream()); in.read(content); license = new String(content); } catch (IOException ioe) { Config.trace("Got exception when reading " + Config.getLicenseResource() + ": " + ioe); return false; } // Build dialog JTextArea ta = new JTextArea(license); ta.setEditable(false); final JDialog jd = new JDialog(_installerFrame, true); Container comp = jd.getContentPane(); jd.setTitle(Config.getLicenseDialogTitle()); comp.setLayout(new BorderLayout(10, 10)); comp.add(new JScrollPane(ta), "Center"); Box box = new Box(BoxLayout.X_AXIS); box.add(box.createHorizontalStrut(10)); box.add(new JLabel(Config.getLicenseDialogQuestionString())); box.add(box.createHorizontalGlue()); JButton acceptButton = new JButton(Config.getLicenseDialogAcceptString()); JButton exitButton = new JButton(Config.getLicenseDialogExitString()); box.add(acceptButton); box.add(box.createHorizontalStrut(10)); box.add(exitButton); box.add(box.createHorizontalStrut(10)); jd.getRootPane().setDefaultButton(acceptButton); Box box2 = new Box(BoxLayout.Y_AXIS); box2.add(box); box2.add(box2.createVerticalStrut(5)); comp.add(box2, "South"); jd.pack(); final boolean accept[] = new boolean[1]; acceptButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { accept[0] = true; jd.hide(); jd.dispose(); } }); exitButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { accept[0] = false; jd.hide(); jd.dispose(); } }); // Apply any defaults the user may have, constraining to the size // of the screen, and default (packed) size. Rectangle size = new Rectangle(0, 0, 500, 300); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); size.width = Math.min(screenSize.width, size.width); size.height = Math.min(screenSize.height, size.height); // Center the window jd.setBounds( (screenSize.width - size.width) / 2, (screenSize.height - size.height) / 2, size.width, size.height); // Show dialog jd.show(); return accept[0]; }
private void jbInit() throws Exception { titledBorder1 = new TitledBorder(""); this.setLayout(baseLayout); double[][] lower_size = { {TableLayout.PREFERRED, TableLayout.FILL, 25}, {25, 25, TableLayout.FILL} }; mLowerPanelLayout = new TableLayout(lower_size); mLowerPanel.setLayout(mLowerPanelLayout); double[][] dir_size = { {TableLayout.FILL, TableLayout.PREFERRED}, {TableLayout.PREFERRED, TableLayout.FILL} }; mDirectionsPanelLayout = new TableLayout(dir_size); mDirectionsPanel.setLayout(mDirectionsPanelLayout); // Try to get icons for the toolbar buttons try { ClassLoader loader = getClass().getClassLoader(); mAddIcon = new ImageIcon(loader.getResource(COMMON_IMG_ROOT + "/add.gif")); mRemoveIcon = new ImageIcon(loader.getResource(COMMON_IMG_ROOT + "/remove.gif")); mDisabledRemoveIcon = new ImageIcon(loader.getResource(COMMON_IMG_ROOT + "/remove_disabled.gif")); mAddNodeBtn.setIcon(mAddIcon); mRemoveNodeBtn.setIcon(mRemoveIcon); mRemoveNodeBtn.setDisabledIcon(mDisabledRemoveIcon); } catch (Exception e) { // Ack! No icons. Use text labels instead mAddNodeBtn.setText("Add"); mRemoveNodeBtn.setText("Remove"); } /* mAddNodeBtn.setMaximumSize(new Dimension(130, 33)); mAddNodeBtn.setMinimumSize(new Dimension(130, 33)); mAddNodeBtn.setPreferredSize(new Dimension(130, 33)); mAddNodeBtn.setText("Add Node"); */ mAddNodeBtn.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { mAddNodeBtn_actionPerformed(e); } }); /* mRemoveNodeBtn.setMaximumSize(new Dimension(130, 33)); mRemoveNodeBtn.setMinimumSize(new Dimension(130, 33)); mRemoveNodeBtn.setPreferredSize(new Dimension(130, 33)); mRemoveNodeBtn.setText("Remove Node"); */ mRemoveNodeBtn.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { mRemoveNode(); } }); mHostnameLabel.setHorizontalAlignment(SwingConstants.TRAILING); mHostnameLabel.setLabelFor(mHostnameField); mHostnameLabel.setText("Hostname:"); mHostnameField.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { mAddNodeBtn_actionPerformed(e); } }); mDirectionsPanel.setBorder(BorderFactory.createEtchedBorder()); mTitleLabel.setFont(new java.awt.Font("Serif", 1, 20)); mTitleLabel.setHorizontalAlignment(SwingConstants.CENTER); mTitleLabel.setText("Add Cluster Nodes"); mDirectionsLabel.setText("Click on the add button to add nodes to your cluster configuration."); mDirectionsLabel.setLineWrap(true); mDirectionsLabel.setEditable(false); mDirectionsLabel.setBackground(mTitleLabel.getBackground()); baseLayout.setHgap(5); baseLayout.setVgap(5); mLowerPanel.add( mHostnameLabel, new TableLayoutConstraints(0, 0, 0, 0, TableLayout.FULL, TableLayout.FULL)); mLowerPanel.add( mHostnameField, new TableLayoutConstraints(1, 0, 1, 0, TableLayout.FULL, TableLayout.FULL)); mLowerPanel.add( mListScrollPane1, new TableLayoutConstraints(0, 1, 1, 2, TableLayout.FULL, TableLayout.FULL)); mLowerPanel.add( mAddNodeBtn, new TableLayoutConstraints(2, 0, 2, 0, TableLayout.FULL, TableLayout.FULL)); mLowerPanel.add( mRemoveNodeBtn, new TableLayoutConstraints(2, 1, 2, 1, TableLayout.FULL, TableLayout.FULL)); this.add(mLowerPanel, BorderLayout.CENTER); mListScrollPane1.getViewport().add(lstNodes, null); mDirectionsPanel.add( mTitleLabel, new TableLayoutConstraints(0, 0, 0, 0, TableLayout.FULL, TableLayout.FULL)); mDirectionsPanel.add( mDirectionsLabel, new TableLayoutConstraints(0, 1, 0, 1, TableLayout.FULL, TableLayout.FULL)); mDirectionsPanel.add( mIconLabel, new TableLayoutConstraints(1, 0, 1, 1, TableLayout.FULL, TableLayout.FULL)); this.add(mDirectionsPanel, BorderLayout.NORTH); }
/** Load the specified icon from the pathname on the classpath. */ private static ImageIcon loadIcon(String pathname) { ClassLoader jarLoader = IssuesBrowser.class.getClassLoader(); URL url = jarLoader.getResource(pathname); if (url == null) return null; return new ImageIcon(url); }
public static Image load(String res) throws IOException { ClassLoader cl = Utility.class.getClassLoader(); return (ImageIO.read(cl.getResource(res))); }
/** Unpacks a resource to a temp. file */ public static File unpackInstaller(String resourceName) { // Array to hold all results (this code is slightly more // generally that it needs to be) File[] results = new File[1]; URL[] urls = new URL[1]; // Determine size of download ClassLoader cl = Main.class.getClassLoader(); urls[0] = cl.getResource(Config.getInstallerResource()); if (urls[0] == null) { Config.trace("Could not find resource: " + Config.getInstallerResource()); return null; } int totalSize = 0; int totalRead = 0; for (int i = 0; i < urls.length; i++) { if (urls[i] != null) { try { URLConnection connection = urls[i].openConnection(); totalSize += connection.getContentLength(); } catch (IOException ioe) { Config.trace("Got exception: " + ioe); return null; } } } // Unpack each file for (int i = 0; i < urls.length; i++) { if (urls[i] != null) { // Create temp. file to store unpacked file in InputStream in = null; OutputStream out = null; try { // Use extension from URL (important for dll files) String extension = new File(urls[i].getFile()).getName(); int lastdotidx = (extension != null) ? extension.lastIndexOf('.') : -1; if (lastdotidx == -1) { extension = ".dat"; } else { extension = extension.substring(lastdotidx); } // Create output stream results[i] = File.createTempFile("jre", extension); results[i].deleteOnExit(); out = new FileOutputStream(results[i]); // Create inputstream URLConnection connection = urls[i].openConnection(); in = connection.getInputStream(); int read = 0; byte[] buf = new byte[BUFFER_SIZE]; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); // Notify delegate totalRead += read; if (totalRead > totalSize && totalSize != 0) totalSize = totalRead; // Update UI if (totalSize != 0) { int percent = (100 * totalRead) / totalSize; setStepText(STEP_UNPACK, Config.getWindowStepProgress(STEP_UNPACK, percent)); } } } catch (IOException ie) { Config.trace("Got exception while downloading resource: " + ie); for (int j = 0; j < results.length; j++) { if (results[j] != null) results[j].delete(); } return null; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException io) { /* ignore */ } } } } setStepText(STEP_UNPACK, Config.getWindowStep(STEP_UNPACK)); return results[0]; }