JPanel not showing background image

为君一笑 提交于 2019-12-20 03:20:02

问题


It is very simple program and i have tried my best but the JPanel doesn't come up with a background image. I just want a simple background image on my panel.

Here is my code:

import javax.swing.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.Graphics;

class PanelEx extends JPanel
{
    BufferedImage img;

    PanelEx()
    {
        try
        {
            img = ImageIO.read(new File("C:/Users/Pictures/s_4261.jpg"));
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
    public void printComponent(Graphics g)
    {
        g.drawImage(img,0,0,null);
    }
}

class JPanelEx2 extends JFrame
{
    PanelEx pe;

    public static void main(String args[])
    {
        new JPanelEx2();
    }

    JPanelEx2()
    {
        pe = new PanelEx();

        add(pe);
        setTitle("JPanel Title");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(320,240);
        setVisible(true);
    }
}

Thanks in advance


回答1:


Replace

public void printComponent(Graphics g) {

with

@Override
public void paintComponent(Graphics g) {
  super.paintComponent(g);



回答2:


Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.

See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:

  1. scaled
  2. tiled
  3. actual


来源:https://stackoverflow.com/questions/32476698/jpanel-not-showing-background-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!