Java 在Swing GUI中清除ImageIcon和相关操作

Java 在Swing GUI中清除ImageIcon和相关操作,java,swing,url,user-interface,imageicon,Java,Swing,Url,User Interface,Imageicon,我正在尝试向基本SUN(Oracle)Java Swing ImageIcon gallery演示添加web URL启动功能: 要求 其目的是创建一个Swing GUI web链接启动器,该启动器能够使用JRE 1.6+桌面API启动器功能通过用户的默认web浏览器启动链接,并根据上次单击的图像打开不同的URL 问题 我似乎遇到的问题是,每当在ThumbnailAction构造函数中创建一个新的ImageIcon时,它似乎并没有破坏以前的图像,而是简单地在上面绘制。不必要的副作用是旧图像的鼠标

我正在尝试向基本SUN(Oracle)Java Swing ImageIcon gallery演示添加web URL启动功能:

要求 其目的是创建一个Swing GUI web链接启动器,该启动器能够使用JRE 1.6+桌面API启动器功能通过用户的默认web浏览器启动链接,并根据上次单击的图像打开不同的URL

问题 我似乎遇到的问题是,每当在ThumbnailAction构造函数中创建一个新的ImageIcon时,它似乎并没有破坏以前的图像,而是简单地在上面绘制。不必要的副作用是旧图像的鼠标侦听器和元数据仍然处于活动状态,因此尝试单击以启动URL实际上会加载以前加载的图像的URL以及当前处于焦点的图像的URL。如果您查看控制台打印日志,还可以看到鼠标多次插入和退出fire,到目前为止,每个已交换的图像一次。因此,如果用户进行3或4次交换,他们将启动那么多URL。不是预期的效果

如果有人知道问题所在,我们将不胜感激,以下是我对“”文件的修改(更新日期:2012-01-31):

/*
*版权所有(c)1995年、2008年,Oracle和/或其附属公司。版权所有。
*
*以源代码和二进制形式重新分发和使用,带或不带
*如果满足以下条件,则允许进行修改
*满足以下条件:
*
*-源代码的重新分发必须保留上述版权
*请注意,此条件列表和以下免责声明。
*
*-二进制形式的重新分发必须复制上述版权
*请注意,此条件列表和中的以下免责声明
*随分发提供的文件和/或其他材料。
*
*-Oracle的名称或其子公司的名称
*贡献者可用于支持或推广衍生产品
*未经事先书面许可,不得使用本软件。
*
*本软件由版权所有人和贡献者“作为
*以及任何明示或暗示的保证,包括但不限于:,
*对特定产品的适销性和适用性的默示保证
*目的是否认。在任何情况下,版权所有人或
*出资人对任何直接、间接、附带、特殊、,
*惩戒性或间接损害(包括但不限于,
*替代货物或服务的采购;使用、数据或服务的损失
*利润;或业务中断),无论是何种原因造成的
*责任,无论是合同责任、严格责任还是侵权责任(包括
*因使用本文件而产生的任何疏忽或其他原因)
*软件,即使已告知此类损坏的可能性。
*/ 
包装组件;
导入java.awt.BasicStroke;
导入java.awt.BorderLayout;
导入java.awt.Color;
导入java.awt.Component;
导入java.awt.Desktop;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.Image;
导入java.awt.RenderingHints;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.event.MouseEvent;
导入java.awt.event.MouseListener;
导入java.awt.image.buffereImage;
导入java.io.IOException;
导入java.net.URI;
导入java.net.URISyntaxException;
导入java.util.ArrayList;
导入java.util.Collection;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Map;
导入java.util.Set;
导入java.util.TreeSet;
导入javax.swing.AbstractAction;
导入javax.swing.BorderFactory;
导入javax.swing.Box;
导入javax.swing.Icon;
导入javax.swing.ImageIcon;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JToolBar;
导入javax.swing.SwingUtilities;
导入javax.swing.SwingWorker;
/**
*此应用程序旨在演示如何将图像文件加载到图标中
*用于Swing用户界面。它创建了一个带有缩略图预览的工具栏
*每幅图像的。单击缩略图将显示完整图像
*在主显示区。
*
*IconDemoApp.java需要以下文件:
*以下文件版权归2006 spriggs.net所有,并根据 *知识共享许可证(http://creativecommons.org/licenses/by-sa/3.0/) *
*images/sunw01.jpg
*images/sunw02.jpg
*images/sunw03.jpg
*images/sunw04.jpg
*图片/sunw05.jpg
* *@作者柯林·法根 *@date 7/25/2007 *@version 2.0 */ 公共类IconDemoApp扩展了JFrame{ /** *演示的主要入口点。在“事件”中加载Swing元素 *调度线程”。 * *@param args */ 公共静态void main(字符串参数[]){ SwingUtilities.invokeLater(新的Runnable(){ 公开募捐{ IconDemoApp app=新的IconDemoApp(); app.setVisible(真); } }); } /* *使命号 *有关如何从丢失的图标中恢复的内部类。 *(显示红色X和白色背景的空图像占位符) */ 类MissingIcon实现图标{ 私有整数宽度=32; 私人内部高度=32; 私人基本行程=新基本行程(4); 公共虚空绘制图标(组件c、图形g、整数x、整数y){ Graphics2D g2d=(Graphics2D)g.create(); g2d.setColor(Color.WHITE); g2d.fillRect(x+1,y+1,宽度-2,高度-2); g2d.setColor(Color.BLACK); g2d.drawRect(x+1,y+1,宽度-2,高度-2); g2d.setColor(Color.RED); g2d.设定行程(行程); g2d.绘制线(x+10,y+10,x+宽度-10,y+高度-10); g2d.绘制线(x+10,y+高度-10,x+宽度-10,y+10); g2d.dispose(); } 公共INTG
/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

package components;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.AbstractAction;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

/**
 * This application is intended to demonstrate the loading of image files into icons
 * for use in a Swing user interface. It creates a toolbar with a thumbnail preview
 * of each image.  Clicking on the thumbnail will show the full image
 * in the main display area.
 *
 * IconDemoApp.java requires the following files: <br>
 * The following files are copyright 2006 spriggs.net and licensed under a
 * Creative Commons License (http://creativecommons.org/licenses/by-sa/3.0/)
 * <br>
 * images/sunw01.jpg <br>
 * images/sunw02.jpg <br>
 * images/sunw03.jpg <br>
 * images/sunw04.jpg <br>
 * images/sunw05.jpg <br>
 *
 * @author Collin Fagan
 * @date 7/25/2007
 * @version 2.0
 */
public class IconDemoApp extends JFrame {

    /**
     * Main entry point to the demo. Loads the Swing elements on the "Event
     * Dispatch Thread".
     *
     * @param args
     */
    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                IconDemoApp app = new IconDemoApp();
                app.setVisible(true);
            }
        });
    }

        /* 
     * MissingIcon
     *  Internal class for how to recover from missing icons.
     *  (displays empty image placeholder with red X and white background)
     */
    class MissingIcon implements Icon {

        private int width = 32;
        private int height = 32;

        private BasicStroke stroke = new BasicStroke(4);

        public void paintIcon(Component c, Graphics g, int x, int y) {
            Graphics2D g2d = (Graphics2D) g.create();

            g2d.setColor(Color.WHITE);
            g2d.fillRect(x +1 ,y + 1,width -2 ,height -2);

            g2d.setColor(Color.BLACK);
            g2d.drawRect(x +1 ,y + 1,width -2 ,height -2);

            g2d.setColor(Color.RED);

            g2d.setStroke(stroke);
            g2d.drawLine(x +10, y + 10, x + width -10, y + height -10);
            g2d.drawLine(x +10, y + height -10, x + width -10, y + 10);

            g2d.dispose();
        }

        public int getIconWidth() {
            return width;
        }

        public int getIconHeight() {
            return height;
        }
    }

    /**
     * Default constructor for the demo.
     */
    public IconDemoApp() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Icon Demo: Please Select an Image");

        // A label for displaying the pictures
        photographLabel.setVerticalTextPosition(JLabel.BOTTOM);
        photographLabel.setHorizontalTextPosition(JLabel.CENTER);
        photographLabel.setHorizontalAlignment(JLabel.CENTER);
        photographLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        // We add two glue components. Later in process() we will add thumbnail buttons
        // to the toolbar inbetween thease glue compoents. This will center the
        // buttons in the toolbar.
        buttonBar.add(Box.createGlue());
        buttonBar.add(Box.createGlue());

        add(buttonBar, BorderLayout.SOUTH);
        add(photographLabel, BorderLayout.CENTER);

        setSize(400, 300);

        // this centers the frame on the screen
        setLocationRelativeTo(null);

        // start the image loading SwingWorker in a background thread
        loadimages.execute();
    }

    /**
     * SwingWorker class that loads the images a background thread and calls publish
     * when a new one is ready to be displayed.
     *
     * We use Void as the first SwingWroker param as we do not need to return
     * anything from doInBackground().
     */
    private SwingWorker<Void, ThumbnailAction> loadimages = new SwingWorker<Void, ThumbnailAction>() {

        /**
         * Creates full size and thumbnail versions of the target image files.
         */
        @Override
        protected Void doInBackground() throws Exception {
            for (int i = 0; i < titles.length; i++) {
                ImageIcon icon;
                icon = createImageIcon(imagedir + thumbs[i], titles[i]);

                ThumbnailAction thumbAction;
                if(icon != null){

                    ImageIcon thumbnailIcon = new ImageIcon(getScaledImage(icon.getImage(), 32, 32));

                    thumbAction = new ThumbnailAction(icon, thumbnailIcon, titles[i], descs[i], links[i]);

                }else{
                    // the image failed to load for some reason
                    // so load a placeholder instead
                    thumbAction = new ThumbnailAction(placeholderIcon, placeholderIcon, titles[i], descs[i], links[i]);
                }
                publish(thumbAction);
            }
            // unfortunately we must return something, and only null is valid to
            // return when the return type is void.
            return null;
        }

        /**
         * Process all loaded images.
         */
        @Override
        protected void process(List<ThumbnailAction> chunks) {
            for (ThumbnailAction thumbAction : chunks) {
                JButton thumbButton = new JButton(thumbAction);
                // add the new button BEFORE the last glue
                // this centers the buttons in the toolbar
                buttonBar.add(thumbButton, buttonBar.getComponentCount() - 1);
            }
        }
    };

    /**
     * Creates an ImageIcon if the path is valid.
     * @param String - resource path
     * @param String - description of the file
     */
    protected ImageIcon createImageIcon(String path, String description) {
        java.net.URL imgURL = getClass().getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
        } 
        else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    /**
     * Resizes an image using a Graphics2D object backed by a BufferedImage.
     * @param srcImg - source image to scale
     * @param w - desired width
     * @param h - desired height
     * @return - the new resized image
     */
    private Image getScaledImage(Image srcImg, int w, int h) {
        BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = resizedImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(srcImg, 0, 0, w, h, null);
        g2.dispose();
        return resizedImg;
    }    

    /**
     * Action class that shows the image specified in it's constructor.
     */
    private class ThumbnailAction extends AbstractAction implements MouseListener {

        private Icon displayPhoto; // The icon if the full image we want to display.

        /**
         * @param Icon - The full size photo to show in the button.
         * @param Icon - The thumbnail to show in the button.
         * @param String - The descriptioon of the icon.
         */
        public ThumbnailAction(Icon photo, Icon thumb, String title, String desc, String link) {
            displayPhoto = photo;

            // The short description becomes the title of the window.
            putValue(SHORT_DESCRIPTION, title);

            // The long description becomes the tooltip of a button.
            putValue(LONG_DESCRIPTION, desc);

            // The DEFAULT action on click is to launch this URL
            putValue(DEFAULT, link);             

            // The LARGE_ICON_KEY is the key for setting the icon when an Action is applied to a button.
            putValue(LARGE_ICON_KEY, thumb);            
        }

        /**
         * Shows the full image in the main area and sets the application title.
         */
        public void actionPerformed(ActionEvent e) {
            photographLabel.setIcon(displayPhoto);
            setTitle("Icon Demo - " + getValue(SHORT_DESCRIPTION).toString());
            photographLabel.setToolTipText("<html>" + getValue(LONG_DESCRIPTION)  + "</html>");

            photographLabel.validate();
            photographLabel.updateUI();
            photographLabel.repaint();

            photographLabel.addMouseListener(this); 
        }

        /**
         * Listen for clicks to send user to a URL or launch an application
         * @param e 
         */            
        @Override
        public void mouseClicked(MouseEvent e) {                
            int clicked = e.getClickCount();
            if (clicked > 0) {
                /*************************************/
                /* Code for launching Browser  BEGIN */
                Desktop desktop = null;
                if (Desktop.isDesktopSupported()) {
                    desktop = Desktop.getDesktop();
                }         
                URI uri = null;
                try {
                    uri = new URI((String)this.getValue(DEFAULT)); //pass the URL from ImageIcon to Browser
                    if (desktop.isSupported(Desktop.Action.BROWSE)) {
                        desktop.browse(uri); //url passed
                    }
                    else {
                        System.out.println("Unable to open default browser to: "+uri);
                    }
                }
                catch(IOException ioe) {
                    ioe.printStackTrace();
                }
                catch(URISyntaxException use) {
                    use.printStackTrace();
                }
                /* Code for launching Browser  END */
                /*************************************/
            }
            else {
                System.out.println("Clicked: " + clicked);
            }
        }        

        @Override
        public void mousePressed(MouseEvent e) {
            System.out.println("Mouse pressed (# of clicks: " + e.getClickCount() + ") " + e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            System.out.println("Mouse released (# of clicks: " + e.getClickCount() + ") " + e);
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            System.out.println("Mouse entered: " + e);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            System.out.println("Mouse exited: " + e);
        }        
    }



    private JLabel photographLabel = new JLabel();
    private JToolBar buttonBar = new JToolBar();

    private String imagedir = "images/";

    private MissingIcon placeholderIcon = new MissingIcon();    

    // List of all the image files to load.
    private String[] thumbs = { "sunw01.jpg", "sunw02.jpg", "sunw03.jpg", "sunw04.jpg", "sunw05.jpg"};

    // List of all the descriptions of the image files. These correspond one to one with the image file names
    private String[] titles = { "SunLogo", "Clocktower", "ClocktowerWest", "Mansion", "SunAuditorium" };

    // List of all descriptions (descs) to use as tooltips.
    private String[] descs = { "The Original SUNW Logo", "The Clocktower frontal view", "The Clocktower from the West", "The Mansion on the hill!", "The infamouse Sun campus auditorium"};

    // List of all links to send a user to on click action.
    private String[] links = { "http://example.com/#1", "http://example.com/#2", "http://example.com/#3", "http://example.com/#4", "http://example.com/#5"};

}
myIcon.getImage().flush();
myLabel.setIcon(myIcon); 
for(MouseListener listener : photographLabel.getMouseListeners()) {
   photographLabel.removeMouseListener(listener);
}
photographLabel.addMouseListener(this);