Example usage for javax.swing ImageIcon getImage

List of usage examples for javax.swing ImageIcon getImage

Introduction

In this page you can find the example usage for javax.swing ImageIcon getImage.

Prototype

@Transient
public Image getImage() 

Source Link

Document

Returns this icon's Image.

Usage

From source file:org.clipsmonitor.gui.MapGeneratorTopComponent.java

protected void updateLabel(String name) {

    try {/* ww  w  . j av  a  2 s . c om*/
        ImageIcon icon = new ImageIcon(img.getImage(name));
        Image image = icon.getImage(); // transform it
        Image newimg = image.getScaledInstance(90, 90, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way
        icon = new ImageIcon(newimg); // transform it back
        Icons.setIcon(icon);
        Icons.setToolTipText("A drawing of a " + name.toLowerCase());
        Icons.setText(null);
    } catch (NullPointerException e) {

        if (!img.getMapImg().isEmpty()) {
            Icons.setText("Image not found");
            model.error(e.getLocalizedMessage());
        }
    }
    updateLogArea();
}

From source file:org.cloudml.ui.graph.Visu.java

public void createFrame() {
    final VisualizationViewer<Vertex, Edge> vv = v.getVisualisationViewer();

    vv.getRenderContext().setVertexIconTransformer(new Transformer<Vertex, Icon>() {
        public Icon transform(final Vertex v) {
            return new Icon() {

                public int getIconHeight() {
                    return 40;
                }//from  www .  ja va  2s. c  o  m

                public int getIconWidth() {
                    return 40;
                }

                public void paintIcon(java.awt.Component c, Graphics g, int x, int y) {
                    ImageIcon img;
                    if (v.getType() == "node") {
                        img = new ImageIcon(this.getClass().getResource("/server.png"));
                    } else if (v.getType() == "platform") {
                        img = new ImageIcon(this.getClass().getResource("/dbms.png"));
                    } else {
                        img = new ImageIcon(this.getClass().getResource("/soft.png"));
                    }
                    ImageObserver io = new ImageObserver() {

                        public boolean imageUpdate(Image img, int infoflags, int x, int y, int width,
                                int height) {
                            // TODO Auto-generated method stub
                            return false;
                        }
                    };
                    g.drawImage(img.getImage(), x, y, getIconHeight(), getIconWidth(), io);

                    if (!vv.getPickedVertexState().isPicked(v)) {
                        g.setColor(Color.black);
                    } else {
                        g.setColor(Color.red);

                        properties.setModel(new CPIMTable(v));
                        runtimeProperties.setModel(new CPSMTable(v));
                    }
                    g.drawString(v.getName(), x - 10, y + 50);
                }
            };
        }
    });

    // create a frame to hold the graph
    final JFrame frame = new JFrame();
    Container content = frame.getContentPane();
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    content.add(panel, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final ModalGraphMouse gm = new DefaultModalGraphMouse<Integer, Number>();
    vv.setGraphMouse(gm);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton save = new JButton("save");
    save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            int returnVal = fc.showDialog(frame, "save");
            File result = fc.getSelectedFile();
            JsonCodec codec = new JsonCodec();
            OutputStream streamResult;
            try {
                streamResult = new FileOutputStream(result);
                codec.save(dmodel, streamResult);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });
    JButton saveImage = new JButton("save as image");
    saveImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            int returnVal = fc.showDialog(frame, "save");
            File result = fc.getSelectedFile();
            JsonCodec codec = new JsonCodec();
            v.writeJPEGImage(result);
        }
    });
    //WE NEED TO UPDATE THE FACADE AND THE GUI
    JButton load = new JButton("load");
    load.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            int returnVal = fc.showDialog(frame, "load");
            File result = fc.getSelectedFile();
            JsonCodec codec = new JsonCodec();
            try {
                InputStream stream = new FileInputStream(result);
                Deployment model = (Deployment) codec.load(stream);
                dmodel = model;
                v.setDeploymentModel(dmodel);
                ArrayList<Vertex> V = v.drawFromDeploymentModel();
                nodeTypes.removeAll();
                nodeTypes.setModel(fillList());

                properties.setModel(new CPIMTable(V.get(0)));
                runtimeProperties.setModel(new CPSMTable(V.get(0)));

                CommandFactory fcommand = new CommandFactory();
                CloudMlCommand load = fcommand.loadDeployment(result.getPath());
                cml.fireAndWait(load);

            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });
    JButton deploy = new JButton("Deploy!");
    deploy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //cad.deploy(dmodel);
            System.out.println("deploy");
            CommandFactory fcommand = new CommandFactory();
            CloudMlCommand deploy = fcommand.deploy();
            cml.fireAndWait(deploy);
        }
    });

    //right panel
    JPanel intermediary = new JPanel();
    intermediary.setLayout(new BoxLayout(intermediary, BoxLayout.PAGE_AXIS));
    intermediary.setBorder(BorderFactory.createLineBorder(Color.black));

    JLabel jlCPIM = new JLabel();
    jlCPIM.setText("CPIM");

    JLabel jlCPSM = new JLabel();
    jlCPSM.setText("CPSM");

    properties = new JTable(null);
    //properties.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    JTableHeader h = properties.getTableHeader();
    JPanel props = new JPanel();
    props.setLayout(new BorderLayout());
    props.add(new JScrollPane(properties), BorderLayout.CENTER);
    props.add(h, BorderLayout.NORTH);

    runtimeProperties = new JTable(null);
    //runtimeProperties.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    JTableHeader h2 = runtimeProperties.getTableHeader();
    JPanel runProps = new JPanel();
    runProps.setLayout(new BorderLayout());
    runProps.add(h2, BorderLayout.NORTH);
    runProps.add(new JScrollPane(runtimeProperties), BorderLayout.CENTER);

    intermediary.add(jlCPIM);
    intermediary.add(props);
    intermediary.add(jlCPSM);
    intermediary.add(runProps);

    content.add(intermediary, BorderLayout.EAST);

    //Left panel
    JPanel selection = new JPanel();
    JLabel nodes = new JLabel();
    nodes.setText("Types");
    selection.setLayout(new BoxLayout(selection, BoxLayout.PAGE_AXIS));
    nodeTypes = new JList(fillList());
    nodeTypes.setLayoutOrientation(JList.VERTICAL);
    nodeTypes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    nodeTypes.setVisibleRowCount(10);
    JScrollPane types = new JScrollPane(nodeTypes);
    types.setPreferredSize(new Dimension(150, 80));
    selection.add(nodes);
    selection.add(types);

    content.add(selection, BorderLayout.WEST);

    ((DefaultModalGraphMouse<Integer, Number>) gm)
            .add(new MyEditingGraphMousePlugin(0, vv, v.getGraph(), nodeTypes, dmodel));
    JPanel controls = new JPanel();
    controls.add(plus);
    controls.add(minus);
    controls.add(save);
    controls.add(saveImage);
    controls.add(load);
    controls.add(deploy);
    controls.add(((DefaultModalGraphMouse<Integer, Number>) gm).getModeComboBox());
    content.add(controls, BorderLayout.SOUTH);

    frame.pack();
    frame.setVisible(true);
}

From source file:org.echocat.velma.Resources.java

@Nonnull
protected List<? extends Image> loadIcons(@Nonnull List<URL> iconUrls) {
    final List<Image> result = new ArrayList<>();
    for (URL iconUrl : iconUrls) {
        final ImageIcon image = new ImageIcon(iconUrl);
        if (image.getIconHeight() >= 0) {
            result.add(image.getImage());
        }/*  w  ww  .  j  a  va  2  s  .  c  o  m*/
    }
    return unmodifiableList(result);
}

From source file:org.genedb.jogra.plugins.TermRationaliser.java

/**
 * Return a new JFrame which is the main interface to the Rationaliser.
 *//*from   w w  w  . ja  v  a2 s .c om*/
public JFrame getMainPanel() {

    /* JFRAME */
    frame.setTitle(WINDOW_TITLE);
    frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    frame.setLayout(new BorderLayout());

    /* MENU */
    JMenuBar menuBar = new JMenuBar();

    JMenu actions_menu = new JMenu("Actions");
    JMenuItem actions_mitem_1 = new JMenuItem("Refresh lists");
    actions_mitem_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            initModels();
        }
    });
    actions_menu.add(actions_mitem_1);

    JMenu about_menu = new JMenu("About");
    JMenuItem about_mitem_1 = new JMenuItem("About");
    about_mitem_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            JOptionPane.showMessageDialog(null,
                    "Term Rationaliser \n" + "Wellcome Trust Sanger Institute, UK \n" + "2009",
                    "Term Rationaliser", JOptionPane.PLAIN_MESSAGE);
        }
    });
    about_menu.add(about_mitem_1);

    menuBar.add(about_menu);
    menuBar.add(actions_menu);
    frame.add(menuBar, BorderLayout.NORTH);

    /* MAIN BOX */
    Box center = Box.createHorizontalBox(); //A box that displays contents from left to right
    center.add(Box.createHorizontalStrut(5)); //Invisible fixed-width component

    /* FROM LIST AND PANEL */
    fromList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); //Allow multiple products to be selected 
    fromList.addKeyListener(new KeyListener() {
        @Override
        public void keyPressed(KeyEvent arg0) {
            if (arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
                synchroniseLists(fromList, toList); //synchronise from left to right
            }
        }

        @Override
        public void keyReleased(KeyEvent arg0) {
        }

        @Override
        public void keyTyped(KeyEvent arg0) {
        }
    });

    Box fromPanel = this.createRationaliserPanel(FROM_LIST_NAME, fromList); //Box on left hand side
    fromPanel.add(Box.createVerticalStrut(55)); //Add some space
    center.add(fromPanel); //Add to main box
    center.add(Box.createHorizontalStrut(3)); //Add some space

    /* MIDDLE PANE */
    Box middlePane = Box.createVerticalBox();

    ClassLoader classLoader = this.getClass().getClassLoader(); //Needed to access the images later on
    ImageIcon leftButtonIcon = new ImageIcon(classLoader.getResource("left_arrow.gif"));
    ImageIcon rightButtonIcon = new ImageIcon(classLoader.getResource("right_arrow.gif"));

    leftButtonIcon = new ImageIcon(leftButtonIcon.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH)); //TODO: Investigate simpler way to resize an icon!
    rightButtonIcon = new ImageIcon(rightButtonIcon.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH)); //TODO: Investigate simpler way to resize an icon!

    JButton rightSynch = new JButton(rightButtonIcon);
    rightSynch.setToolTipText("Synchronise TO list. \n Shortcut: Right-arrow key");

    rightSynch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            synchroniseLists(fromList, toList);
        }
    });

    JButton leftSynch = new JButton(leftButtonIcon);
    leftSynch.setToolTipText("Synchronise FROM list. \n Shortcut: Left-arrow key");

    leftSynch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            synchroniseLists(toList, fromList);
        }
    });

    middlePane.add(rightSynch);
    middlePane.add(leftSynch);

    center.add(middlePane); //Add middle pane to main box
    center.add(Box.createHorizontalStrut(3));

    /* TO LIST AND PANEL */
    toList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //Single product selection in TO list
    toList.addKeyListener(new KeyListener() {
        @Override
        public void keyPressed(KeyEvent arg0) {
            if (arg0.getKeyCode() == KeyEvent.VK_LEFT) {
                synchroniseLists(toList, fromList); //synchronise from right to left
            }
        }

        @Override
        public void keyReleased(KeyEvent arg0) {
        }

        @Override
        public void keyTyped(KeyEvent arg0) {
        }
    });

    Box toPanel = this.createRationaliserPanel(TO_LIST_NAME, toList);

    Box newTerm = Box.createVerticalBox();

    textField = new JTextArea(1, 1); //textfield to let the user edit the name of an existing term
    textField.setMaximumSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize().height, 10));

    textField.setForeground(Color.BLUE);
    JScrollPane jsp = new JScrollPane(textField); //scroll pane so that there is a horizontal scrollbar
    jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

    newTerm.add(jsp);
    TitledBorder editBorder = BorderFactory.createTitledBorder("Edit term name");
    editBorder.setTitleColor(Color.DARK_GRAY);
    newTerm.setBorder(editBorder);
    toPanel.add(newTerm); //add textfield to panel

    center.add(toPanel); //add panel to main box
    center.add(Box.createHorizontalStrut(5));

    frame.add(center); //add the main panel to the frame

    initModels(); //load the lists with data

    /* BOTTOM HALF OF FRAME */
    Box main = Box.createVerticalBox();
    TitledBorder border = BorderFactory.createTitledBorder("Information");
    border.setTitleColor(Color.DARK_GRAY);

    /* INFORMATION BOX */
    Box info = Box.createVerticalBox();

    Box scope = Box.createHorizontalBox();
    scope.add(Box.createHorizontalStrut(5));
    scope.add(scopeLabel); //label showing the scope of the terms
    scope.add(Box.createHorizontalGlue());

    Box productCount = Box.createHorizontalBox();
    productCount.add(Box.createHorizontalStrut(5));
    productCount.add(productCountLabel); //display the label showing the number of terms
    productCount.add(Box.createHorizontalGlue());

    info.add(scope);
    info.add(productCount);
    info.setBorder(border);

    /* ACTION BUTTONS */
    Box actionButtons = Box.createHorizontalBox();
    actionButtons.add(Box.createHorizontalGlue());
    actionButtons.add(Box.createHorizontalStrut(10));

    JButton findFix = new JButton(new FindClosestMatchAction());
    actionButtons.add(findFix);
    actionButtons.add(Box.createHorizontalStrut(10));

    RationaliserAction ra = new RationaliserAction();
    // RationaliserAction2 ra2 = new RationaliserAction2();
    JButton go = new JButton(ra);
    actionButtons.add(go);
    actionButtons.add(Box.createHorizontalGlue());

    /* MORE INFORMATION TOGGLE */
    Box buttonBox = Box.createHorizontalBox();
    final JButton toggle = new JButton("Hide information <<");

    buttonBox.add(Box.createHorizontalStrut(5));
    buttonBox.add(toggle);
    buttonBox.add(Box.createHorizontalGlue());

    Box textBox = Box.createHorizontalBox();

    final JScrollPane scrollPane = new JScrollPane(information);
    scrollPane.setPreferredSize(new Dimension(frame.getWidth(), 100));
    scrollPane.setVisible(true);
    textBox.add(Box.createHorizontalStrut(5));
    textBox.add(scrollPane);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            if (toggle.getText().equals("Show information >>")) {
                scrollPane.setVisible(true);
                toggle.setText("Hide information <<");
                frame.setPreferredSize(new Dimension(frame.getWidth(), frame.getHeight() + 100));
                frame.pack();
            } else if (toggle.getText().equals("Hide information <<")) {
                scrollPane.setVisible(false);
                toggle.setText("Show information >>");
                frame.setPreferredSize(new Dimension(frame.getWidth(), frame.getHeight() - 100));
                frame.pack();
            }
        }
    };
    toggle.addActionListener(actionListener);

    main.add(Box.createVerticalStrut(5));
    main.add(info);
    main.add(Box.createVerticalStrut(5));
    main.add(Box.createVerticalStrut(5));
    main.add(actionButtons);
    main.add(Box.createVerticalStrut(10));
    main.add(buttonBox);
    main.add(textBox);

    frame.add(main, BorderLayout.SOUTH);
    frame.pack();
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    frame.setVisible(true);
    //initModels();

    return frame;
}

From source file:org.jajuk.ui.thumbnails.LastFmAlbumThumbnail.java

/**
 * Long part of the populating process. Longest parts (images download) should
 * have already been done by the caller outside the EDT. we only pop the image
 * from the cache here./*from  w w w . j  ava 2s .  co  m*/
 */
private void preLoad() {
    try {
        // Check if album image is null
        String albumUrl = album.getBigCoverURL();
        if (StringUtils.isBlank(albumUrl)) {
            return;
        }
        // Download thumb
        URL remote = new URL(albumUrl);
        // Download image and store file reference (to generate the
        // popup thumb for ie)
        fCover = DownloadManager.downloadToCache(remote);
        if (!fCover.exists()) {
            Log.warn("Cache file not found: {{" + fCover.getAbsolutePath() + "}}");
            return;
        }
        if (fCover.length() == 0) {
            Log.warn("Cache file has zero bytes: {{" + fCover.getAbsolutePath() + "}}");
            return;
        }
        BufferedImage image = ImageIO.read(fCover);
        if (image == null) {
            Log.warn("Could not read cover from: {{" + fCover.getAbsolutePath() + "}}");
            return;
        }
        ImageIcon downloadedImage = new ImageIcon(image);
        ii = UtilGUI.getScaledImage(downloadedImage, 100);
        // Free images memory
        downloadedImage.getImage().flush();
        image.flush();
    } catch (FileNotFoundException e) {
        // only report a warning for FileNotFoundException and do not show a
        // stack trace in the logfile as it is happening frequently
        Log.warn("Could not load image, no content found at address: {{" + e.getMessage() + "}}");
    } catch (SocketTimeoutException e) {
        // only report a warning for FileNotFoundException and do not show a
        // stacktrace in the logfile as it is happening frequently
        Log.warn("Could not load image, timed out while reading address: {{" + e.getMessage() + "}}");
    } catch (IOException e) {
        if (e.getMessage().contains(" 403 ")) {
            Log.warn("Could not access webpage, returned error 403: " + e.getMessage());
        } else {
            Log.error(e);
        }
    } catch (Exception e) {
        Log.error(e);
        // check for empty file to remove invalid cache entries
        if (fCover.exists() && fCover.length() == 0) {
            Log.warn("Removing empty file from cache: " + fCover.getAbsolutePath());
            if (!fCover.delete()) {
                Log.warn("Error removing file: " + fCover.getAbsolutePath());
            }
        }
    }
}

From source file:org.jajuk.ui.thumbnails.LastFmArtistThumbnail.java

/**
 * Long part of the populating process. Longest parts (images download) should
 * have already been done by the caller outside the EDT. we only pop the image
 * from the cache here./*  w  w w . j a  va  2  s  .c o m*/
 */
private void preLoad() {
    try {
        // Check if artist is null
        String artistUrl = artist.getImageUrl();
        if (StringUtils.isBlank(artistUrl)) {
            return;
        }
        // Download thumb
        URL remote = new URL(artistUrl);
        // Download the picture and store file reference (to
        // generate the popup thumb for ie)
        fCover = DownloadManager.downloadToCache(remote);
        if (fCover == null) {
            Log.warn("Could not read remote file: {{" + remote.toString() + "}}");
            return;
        }
        BufferedImage image = ImageIO.read(fCover);
        if (image == null) {
            Log.warn("Could not read image data in file: {{" + fCover + "}}");
            return;
        }
        ImageIcon downloadedImage = new ImageIcon(image);
        // In artist view, do not reduce artist picture
        if (isArtistView()) {
            ii = downloadedImage;
        } else {
            ii = UtilGUI.getScaledImage(downloadedImage, 100);
        }
        // Free images memory
        downloadedImage.getImage().flush();
        image.flush();
    } catch (IIOException e) {
        // report IIOException only as warning here as we can expect this to
        // happen frequently with images on the net
        Log.warn("Could not read image: {{" + artist.getImageUrl() + "}} Cache: {{" + fCover + "}}",
                e.getMessage());
    } catch (UnknownHostException e) {
        Log.warn("Could not contact host for loading images: {{" + e.getMessage() + "}}");
    } catch (Exception e) {
        Log.error(e);
    }
}

From source file:org.jajuk.ui.views.CoverView.java

/**
 * Long action to compute image to display (download, resizing...)
 * //from   w  w w . j  a va 2s. co  m
 * @param index 
 * 
 * @throws JajukException the jajuk exception
 */
private void prepareDisplay(final int index) throws JajukException {
    // find next correct cover
    Cover cover = null;
    ImageIcon icon = null;
    try {
        cover = alCovers.get(index); // take image at the given index
        Log.debug("Display cover: " + cover + " at index :" + index);
        Image img = cover.getImage();
        // Never mirror our no cover image
        if (cover.getType().equals(CoverType.NO_COVER)) {
            icon = new ImageIcon(img);
        } else {
            if (
            // should we mirror in our GUI
            (includeControls && Conf.getBoolean(Const.CONF_COVERS_MIRROW_COVER))
                    // should we mirror in fullscreen mode
                    || (!includeControls && Conf.getBoolean(Const.CONF_COVERS_MIRROW_COVER_FS_MODE))) {
                icon = new ImageIcon(UtilGUI.get3dImage(img));
            } else {
                icon = new ImageIcon(img);
            }
        }
        if (icon.getIconHeight() == 0 || icon.getIconWidth() == 0) {
            throw new JajukException(0, "Wrong picture, size is null");
        }
    } catch (final FileNotFoundException e) {
        // do not display a stacktrace for FileNotfound as we expect this in cases
        // where the picture is gone on the net
        Log.warn("Cover image not found at URL: " + (cover == null ? "<null>" : cover.getURL().toString()));
        throw new JajukException(0, e);
    } catch (final UnknownHostException e) {
        // do not display a stacktrace for HostNotFound as we expect this in cases
        // where the whole server is gone on the net
        Log.warn("Cover image not found at URL: " + (cover == null ? "<null>" : cover.getURL().toString()));
        throw new JajukException(0, e);
    } catch (final IOException e) { // this cover cannot be loaded
        Log.error(e);
        throw new JajukException(0, e);
    } catch (final InterruptedException e) { // this cover cannot be loaded
        Log.error(e);
        throw new JajukException(0, e);
    }
    // We apply a 90% of space availability to avoid image cut-offs (see #1283)
    final int iDisplayAreaHeight = (int) (0.9f * CoverView.this.getHeight() - 30);
    final int iDisplayAreaWidth = (int) (0.9f * CoverView.this.getWidth() - 10);
    // check minimum sizes
    if ((iDisplayAreaHeight < 1) || (iDisplayAreaWidth < 1)) {
        return;
    }
    int iNewWidth;
    int iNewHeight;
    if (iDisplayAreaHeight > iDisplayAreaWidth) {
        // Width is smaller than height : try to optimize height
        iNewHeight = iDisplayAreaHeight; // take all possible height
        // we check now if width will be visible entirely with optimized
        // height
        final float fHeightRatio = (float) iNewHeight / icon.getIconHeight();
        if (icon.getIconWidth() * fHeightRatio <= iDisplayAreaWidth) {
            iNewWidth = (int) (icon.getIconWidth() * fHeightRatio);
        } else {
            // no? so we optimize width
            iNewWidth = iDisplayAreaWidth;
            iNewHeight = (int) (icon.getIconHeight() * ((float) iNewWidth / icon.getIconWidth()));
        }
    } else {
        // Height is smaller or equal than width : try to optimize width
        iNewWidth = iDisplayAreaWidth; // take all possible width
        // we check now if height will be visible entirely with
        // optimized width
        final float fWidthRatio = (float) iNewWidth / icon.getIconWidth();
        if (icon.getIconHeight() * fWidthRatio <= iDisplayAreaHeight) {
            iNewHeight = (int) (icon.getIconHeight() * fWidthRatio);
        } else {
            // no? so we optimize width
            iNewHeight = iDisplayAreaHeight;
            iNewWidth = (int) (icon.getIconWidth() * ((float) iNewHeight / icon.getIconHeight()));
        }
    }
    // Note that at this point, the image is fully loaded (done in the ImageIcon constructor)
    ii = UtilGUI.getResizedImage(icon, iNewWidth, iNewHeight);
    // Free memory of source image, removing this causes severe memory leaks ! (tested)
    icon.getImage().flush();
}

From source file:org.jets3t.gui.GuiUtils.java

/**
 * Loads an icon image from the classpath and sets the icon of the component.
 *
 * @param component//from w w  w.  j  av a2  s.  c  o  m
 * the component to apply the icon to, supported components are: JMenuItem, JButton, JLabel, Frame.
 * @param iconResourcePath
 * the path to an icon image in the classpath.
 *
 * @return
 * true if the icon was found and applied to the component
 */
public boolean applyIcon(Object component, String iconResourcePath) {
    ImageIcon icon = (ImageIcon) cachedImageIcons.get(iconResourcePath);

    if (icon == null) {
        // Icon is not yet cached, load it as a resource.
        URL iconUrl = this.getClass().getResource(iconResourcePath);
        if (iconUrl == null) {
            // Try loading icon using an encoded URL, which can help if the path uses characters
            // that should be URL-encoded (eg '+')
            try {
                int firstSlashIndex = iconResourcePath.indexOf('/', 1);
                String firstPathComponent = iconResourcePath.substring(0, firstSlashIndex);
                String pathRemainder = iconResourcePath.substring(firstSlashIndex);
                URL baseUrl = this.getClass().getResource(firstPathComponent);
                iconUrl = new URL(baseUrl.toString() + RestUtils.encodeUrlPath(pathRemainder, "/"));
                iconUrl.getContent(); // Check whether there is data availabel at the built path.
            } catch (Exception e) {
                log.warn("Unable to load icon with resource path: " + iconResourcePath);
                return false;
            }
        }
        if (iconUrl != null) {
            icon = new ImageIcon(iconUrl);
            cachedImageIcons.put(iconResourcePath, icon);
        }
    }

    if (icon != null) {
        if (component instanceof JMenuItem) {
            ((JMenuItem) component).setIcon(icon);
        } else if (component instanceof JButton) {
            ((JButton) component).setIcon(icon);
        } else if (component instanceof JLabel) {
            ((JLabel) component).setIcon(icon);
        } else if (component instanceof Frame) {
            ((Frame) component).setIconImage(icon.getImage());
        } else {
            log.warn("Cannot set icon for unexpected JComponent object: " + component.getClass().getName());
            return false;
        }
        return true;
    } else {
        log.warn("Unable to load icon with resource path: " + iconResourcePath);
        return false;
    }
}

From source file:org.jwebgenerator.views.WorkSpaceWindow.java

public WorkSpaceWindow(String title) throws HeadlessException {
    LOG.info("Creating the workspace panel ...");
    if (StringUtils.isEmpty(title)) {
        setTitle(title);// ww w  .  j a  v  a  2  s  .c o  m
    }

    final Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setSize(dimension);

    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ImageIcon jwebGeneratorIcon = new ImageIcon(JWebGeneratorFolder.ICONS_FOLDER + File.separator + "icon.png");
    setIconImage(jwebGeneratorIcon.getImage());

    getContentPane().add(buildWorkSpaceContent());
    handleUserEvents();
}

From source file:org.lnicholls.galleon.gui.MainFrame.java

public MainFrame(String version) {

    super("Galleon " + version);

    setDefaultCloseOperation(0);//w  ww .  j  a  va2s  . c o m

    JMenuBar menuBar = new JMenuBar();

    menuBar.putClientProperty("jgoodies.headerStyle", HeaderStyle.BOTH);

    menuBar.putClientProperty("jgoodies.windows.borderStyle", BorderStyle.SEPARATOR);

    menuBar.putClientProperty("Plastic.borderStyle", BorderStyle.SEPARATOR);

    JMenu fileMenu = new JMenu("File");

    fileMenu.setMnemonic('F');

    fileMenu.add(new MenuAction("New App...", null, "", new Integer(KeyEvent.VK_N)) {

        public void actionPerformed(ActionEvent event) {

            new AddAppDialog(Galleon.getMainFrame()).setVisible(true);

        }

    });

    fileMenu.addSeparator();

    fileMenu.add(new MenuAction("Properties...", null, "", new Integer(KeyEvent.VK_P)) {

        public void actionPerformed(ActionEvent event) {

            new ServerDialog(Galleon.getMainFrame(), Galleon.getServerConfiguration()).setVisible(true);

        }

    });

    /*
            
    fileMenu.add(new MenuAction("Galleon.tv Account...", null, "", new Integer(KeyEvent.VK_A)) {
            
            
            
       public void actionPerformed(ActionEvent event) {
            
    new DataDialog(Galleon.getMainFrame(), Galleon.getServerConfiguration()).setVisible(true);
            
       }
            
            
            
    });
            
    */

    fileMenu.add(new MenuAction("Download Manager...", null, "", new Integer(KeyEvent.VK_D)) {

        public void actionPerformed(ActionEvent event) {

            new DownloadManagerDialog(Galleon.getMainFrame(), Galleon.getServerConfiguration())
                    .setVisible(true);

        }

    });

    fileMenu.add(new MenuAction("GoBack...", null, "", new Integer(KeyEvent.VK_G)) {

        public void actionPerformed(ActionEvent event) {

            new GoBackDialog(Galleon.getMainFrame(), Galleon.getServerConfiguration()).setVisible(true);

        }

    });

    fileMenu.add(new MenuAction("Music Player...", null, "", new Integer(KeyEvent.VK_M)) {

        public void actionPerformed(ActionEvent event) {

            new MusicPlayerDialog(Galleon.getMainFrame(), Galleon.getServerConfiguration()).setVisible(true);

        }

    });

    fileMenu.add(new MenuAction("ToGo...", null, "", new Integer(KeyEvent.VK_T)) {

        public void actionPerformed(ActionEvent event) {

            new ToGoDialog(Galleon.getMainFrame(), Galleon.getServerConfiguration()).setVisible(true);

        }

    });

    fileMenu.addSeparator();

    fileMenu.add(new MenuAction("Exit", null, "", new Integer(KeyEvent.VK_X)) {

        public void actionPerformed(ActionEvent event) {

            System.exit(0);

        }

    });

    menuBar.add(fileMenu);

    JMenu tutorialMenu = new JMenu("Tutorials");

    tutorialMenu.setMnemonic('T');

    tutorialMenu.putClientProperty("jgoodies.noIcons", Boolean.TRUE);

    tutorialMenu.add(new MenuAction("Properties", null, "", new Integer(KeyEvent.VK_P)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv/content/view/88/48/");

            } catch (Exception ex) {

            }

        }

    });

    tutorialMenu.add(new MenuAction("Music Player", null, "", new Integer(KeyEvent.VK_M)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv/content/view/88/48/");

            } catch (Exception ex) {

            }

        }

    });

    tutorialMenu.addSeparator();

    tutorialMenu.add(new MenuAction("Email", null, "", new Integer(KeyEvent.VK_E)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv/content/view/88/48/");

            } catch (Exception ex) {

            }

        }

    });

    tutorialMenu.add(new MenuAction("Music", null, "", new Integer(KeyEvent.VK_U)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv/content/view/88/48/");

            } catch (Exception ex) {

            }

        }

    });

    tutorialMenu.add(new MenuAction("Podcasting", null, "", new Integer(KeyEvent.VK_O)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv/content/view/88/48/");

            } catch (Exception ex) {

            }

        }

    });

    tutorialMenu.add(new MenuAction("ToGo", null, "", new Integer(KeyEvent.VK_T)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv/content/view/88/48/");

            } catch (Exception ex) {

            }

        }

    });

    menuBar.add(tutorialMenu);

    JMenu helpMenu = new JMenu("Help");

    helpMenu.setMnemonic('H');

    helpMenu.putClientProperty("jgoodies.noIcons", Boolean.TRUE);

    helpMenu.add(new MenuAction("Homepage", null, "", new Integer(KeyEvent.VK_H)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv");

            } catch (Exception ex) {

            }

        }

    });

    helpMenu.add(new MenuAction("Configuration", null, "", new Integer(KeyEvent.VK_C)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv/content/view/93/52/");

            } catch (Exception ex) {

            }

        }

    });

    helpMenu.add(new MenuAction("FAQ", null, "", new Integer(KeyEvent.VK_F)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv/content/section/3/47/");

            } catch (Exception ex) {

            }

        }

    });

    /*
            
    helpMenu.add(new MenuAction("TiVo Community Forum", null, "", new Integer(KeyEvent.VK_T)) {
            
            
            
       public void actionPerformed(ActionEvent event) {
            
    try {
            
       BrowserLauncher.openURL("http://www.tivocommunity.com/tivo-vb/forumdisplay.php?f=35");
            
    } catch (Exception ex) {
            
    }
            
       }
            
            
            
    });
            
    */

    helpMenu.add(new MenuAction("Galleon Forum", null, "", new Integer(KeyEvent.VK_G)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher.openURL("http://galleon.tv/component/option,com_joomlaboard/Itemid,26/");

            } catch (Exception ex) {

            }

        }

    });

    helpMenu.add(new MenuAction("File a bug", null, "", new Integer(KeyEvent.VK_B)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher
                        .openURL("http://sourceforge.net/tracker/?atid=705256&group_id=126291&func=browse");

            } catch (Exception ex) {

            }

        }

    });

    helpMenu.add(new MenuAction("Request a feature", null, "", new Integer(KeyEvent.VK_E)) {

        public void actionPerformed(ActionEvent event) {

            try {

                BrowserLauncher
                        .openURL("http://sourceforge.net/tracker/?atid=705259&group_id=126291&func=browse");

            } catch (Exception ex) {

            }

        }

    });

    helpMenu.addSeparator();

    helpMenu.add(new MenuAction("About...", null, "", new Integer(KeyEvent.VK_A)) {

        public void actionPerformed(ActionEvent event) {

            JOptionPane

                    .showMessageDialog(

                            Galleon.getMainFrame(),

                            "Galleon Version "

                                    + Tools.getVersion()

                                    + "\nJava Version "

                                    + System.getProperty("java.vm.version")

                                    + "\nPublishing Port "

                                    + Galleon.getHttpPort()

                                    + "\nApplication Port "

                                    + Galleon.getPort()

                                    + "\nhttp://galleon.tv\njavahmo@users.sourceforge.net\nCopyright \251 2005, 2006 Leon Nicholls. All Rights Reserved.",

                            "About", JOptionPane.INFORMATION_MESSAGE);

        }

    });

    menuBar.add(helpMenu);

    setJMenuBar(menuBar);

    JComponent content = createContentPane();

    setContentPane(content);

    pack();

    Dimension paneSize = getSize();

    Dimension screenSize = getToolkit().getScreenSize();

    setLocation((screenSize.width - paneSize.width) / 2, (screenSize.height - paneSize.height) / 2);

    URL url = getClass().getClassLoader().getResource("guiicon.gif");

    ImageIcon logo = new ImageIcon(url);

    if (logo != null)

        setIconImage(logo.getImage());

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    addWindowListener(new WindowAdapter() {

        public void windowClosing(WindowEvent e) {

            System.exit(0);

        }

    });

}