繁体   English   中英

具有图像背景的JPanel

[英]JPanel with image background

如何在JPANEL上放置图像背景?

JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2)); 
pDraw.setPreferredSize(new Dimension(600,600)); //size of the JPanel
pDraw.setBackground(Color.RED); //How can I change the background from red color to image?

Image加载到ImageIcon并将其显示在JLabel可能是最简单的,但是:
要将图像直接“绘制”到JPanel,请重写JPanel的paintComponent(Graphics)方法,如下所示:

public void paintComponent(Graphics page)
{
    super.paintComponent(page);
    page.drawImage(img, 0, 0, null);
}

其中img是一个Image (可能通过ImageIO.read()调用加载)。

Graphics#drawImage是一个非常重载的命令,它使您可以高度特定地将图像绘制到组件的方式,数量和位置。

您还可以使用Image#getScaledInstance方法获得“精美效果”并将图像缩放到令人愉悦的Image#getScaledInstance 为了保持图像的纵横比相同, widthheight参数将为-1

用一种更花哨的方式:

public void paintComponent(Graphics page)
{
    super.paintComponent(page);

    int h = img.getHeight(null);
    int w = img.getWidth(null);

    // Scale Horizontally:
    if ( w > this.getWidth() )
    {
        img = img.getScaledInstance( getWidth(), -1, Image.SCALE_DEFAULT );
        h = img.getHeight(null);
    }

    // Scale Vertically:
    if ( h > this.getHeight() )
    {
        img = img.getScaledInstance( -1, getHeight(), Image.SCALE_DEFAULT );
    }

    // Center Images
    int x = (getWidth() - img.getWidth(null)) / 2;
    int y = (getHeight() - img.getHeight(null)) / 2;

    // Draw it
    page.drawImage( img, x, y, null );
}

这是一个解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM