java - 调整窗口上的 ImageIcon 大小

标签 java swing paintcomponent imageicon

这已经困扰我一段时间了,但我似乎无法弄清楚我做错了什么。所以我用图像图标设置面板的背景,但是当我调整窗口大小时,它使 BG 保持相同的大小,并且我在暴露的边缘周围得到了这个巨大的白墙,我想将 bg 拉伸(stretch)为窗口变化

这是我的相关代码

    protected JPanel createRightPane() {
        final ImageIcon BGiconSM = ScaledImageIcon("parchmentTall.jpg", "BG Plate", initalWidth/2, initalHeight);
        final ImageIcon iconSM = ScaledImageIcon("titlebar.png", "Title Bar BG", (initalWidth/3), 40);
        //TODO Parchment image resize
        final JPanel content = new JPanel(new GridBagLayout());
        content.setOpaque(false);

        final JPanel panel = new JPanel(new BorderLayout())                           {
            protected void paintComponent(Graphics g)
            {
                //  Dispaly image at full size
                Image BGicon = BGiconSM.getImage();                 
                g.drawImage(BGicon, 0, 0, null);
                super.paintComponent(g);
            }
        };
        panel.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e){
                Rectangle r = frame.getBounds();
                int h = r.height;
                int w = r.width;
                if (h >= initalHeight){h = initalHeight-30;}                    
                //System.out.println(h);
                //System.out.println(w);
/*                  protected paintComponent(Graphics g)
                {
                    //  Dispaly image at full size
                    Image BGicon = BGiconSM.getImage();                 
                    g.drawImage(BGicon, 0, 0, null);
                    super.paintComponent(g);
                }
*/
            }
        });

最佳答案

问题是,为什么要(调整大小)?您只告诉 Graphics 上下文它应该在组件的左上角 (0x0) 绘制图像。

您应该看看Graphics#drawImage(Image, int, int, int, int, ImageObserver)Graphics2D#drawImage(Image, AffineTransform, ImageObserver)

您还应该看看:

有关缩放图像的不同方法的讨论

您还破坏了油漆链,这导致了“白墙”。在执行任何自定义绘画之前,您应该调用 super.paintComponent

当为了自定义绘制而重写诸如 JPanelJComponent 之类的容器时,您还应该考虑重写 getPreferredSize 方法,这将为布局管理器提供将组件调整为适当的默认大小的方法,而不是使用通常为默认大小的 0x0

关于java - 调整窗口上的 ImageIcon 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25967481/

相关文章:

Java 未捕获 lambda 引发的未经检查的异常

java - 是否存在不需要外部 JAR 的 Java GUI 构建器?

Java 变色图形与定时器

java - 如何绘制到鼠标监听器事件?

java - 在开关中添加图像 - PaintComponent 覆盖

java - 线程中出现异常 "AWT-EventQueue-0"java.lang.NullPointerException 弹跳球

java - JAX-WS 网络服务的 JSON 输出?

java - 实现多线程访问的java映射,每个键只更新一次

Java GridBagLayout 聚集在一行中

java - PaintComponent 方法运行了 3 次