将背景图像添加到面板 [英] Add an Background image to a Panel

查看:154
本文介绍了将背景图像添加到面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 JPanel ,我想添加一张图片作为背景。我该怎么做?

I have a JPanel, and i want to add an image as its background. How can i do that ?

frame = new JFrame("Some frame");
panel1 = new JPanel();
panel1.setBorder(new EmptyBorder(5, 5, 5, 5));
// NEED TO ADD AN IMAGE TO THIS PANEL

panel1.setLayout(cardlayout);
frame.getContentPane().add(panel1);

frame.setLocationByPlatform(true);
frame.setVisible(true);

我需要将图像添加到面板我该怎么办?

I need to add an image to the panel and how can i do it ?

UPDATE 1

    panel1 = new JPanel()
    {
    private static final long serialVersionUID = 1L;

    @Override
    public void paintComponent(Graphics g)
    {

        g.drawImage(Toolkit.getDefaultToolkit().createImage("1.jpg"), 0, 0, null);
    }
};


推荐答案

您需要覆盖方法 paintComponent (a gref =http://docs.oracle.com/javase/6/docs/api/javax/swing/JPanel.html =的图形g) nofollow noreferrer> JPanel 并使用 drawImage() 图形对象 g ,如此示例

You need to override the method paintComponent(Graphics g) of JPanel and use drawImage() on the Graphics object g as in this example.

另外,请通过 @trashgod 查看这两个示例:

Also, check these two examples by @trashgod:


  1. 示例

  2. 示例

  1. example.
  2. example.

这篇关于将背景图像添加到面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆