栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将图标转换为图像

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将图标转换为图像

刚刚找到了一个代码段,如果您想更频繁地包装那些表现不佳的LAF提供的图标,可能会有所帮助:

public static class SafeIcon implements Icon {    private Icon wrappee;    private Icon standIn;    public SafeIcon(Icon wrappee) {        this.wrappee = wrappee;    }    @Override    public int getIconHeight() {        return wrappee.getIconHeight();    }    @Override    public int getIconWidth() {        return wrappee.getIconWidth();    }    @Override    public void paintIcon(Component c, Graphics g, int x, int y) {        if (standIn == this) { paintFallback(c, g, x, y);        } else if (standIn != null) { standIn.paintIcon(c, g, x, y);        } else { try {    wrappee.paintIcon(c, g, x, y);  } catch (ClassCastException e) {     createStandIn(e, x, y);     standIn.paintIcon(c, g, x, y); }        }    }        private void createStandIn(ClassCastException e, int x, int y) {        try { Class<?> clazz = getClass(e); JComponent standInComponent = getSubstitute(clazz); standIn = createImageIcon(standInComponent, x, y);        } catch (Exception e1) { // something went wrong - fallback to this painting standIn = this;        }     }    private Icon createImageIcon(JComponent standInComponent, int x, int y) {        BufferedImage image = new BufferedImage(getIconWidth(),     getIconHeight(), BufferedImage.TYPE_INT_ARGB);          Graphics g = image.createGraphics();          try {   wrappee.paintIcon(standInComponent, g, 0, 0);   return new ImageIcon(image);          } finally {   g.dispose();          }    }        private JComponent getSubstitute(Class<?> clazz) throws IllegalAccessException {        JComponent standInComponent;        try { standInComponent = (JComponent) clazz.newInstance();        } catch (InstantiationException e) { standInComponent = new AbstractButton() { }; ((AbstractButton) standInComponent).setModel(new DefaultButtonModel());        }         return standInComponent;    }    private Class<?> getClass(ClassCastException e) throws ClassNotFoundException {        String className = e.getMessage();        className = className.substring(className.lastIndexOf(" ") + 1);        return Class.forName(className);    }    private void paintFallback(Component c, Graphics g, int x, int y) {        g.drawRect(x, y, getIconWidth(), getIconHeight());        g.drawLine(x, y, x + getIconWidth(), y + getIconHeight());        g.drawLine(x + getIconWidth(), y, x, y + getIconHeight());    }}

要在您的代码段中使用,只需传递任意组件:

    icon = new SafeIcon(icon);    BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);    icon.paintIcon(new JPanel(), image.getGraphics(), 0, 0);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438035.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号