带有图像背景的JPanel

7
如何在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?

我会使用JImagePanel。它应该能够满足你的所有需求。 - dberm22
2个回答

4

最简单的方法是将 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方法对图像进行缩放,使其更加美观。如果将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 );
}

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接