将带有背景图像的 JPanel 添加到 JFrame 并绘制它 [英] Add a JPanel with a background image to a JFrame and paint it

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

问题描述

我正在使用 GUI 开发一个新的 Java 桌面应用程序,我想添加一个带有背景图像的 JPanel.带有图像的 JLabel 将不起作用,因为我将在背景面板顶部添加不同的标签.

I'm working on a new Java Desktop Application using the GUI and I want to add a JPanel with a background image on it. A JLabel with an image won't work because I'm going to be adding different labels on top of the background panel.

所以我想出了这个例子,我想实现它.

So I came up with this example and I want to implement it.

http://www.coderanch.com/how-to/java/BackgroundImageOnJPanel

class BackgroundPanel extends JPanel
{
  Image image;
  public BackgroundPanel()
  {
    try
    {
      image = javax.imageio.ImageIO.read(getClass().getResource("Test.gif"));
    }
    catch (Exception e) { e.printStackTrace(); /*handled in paintComponent()*/ }
  }

  @Override
  protected void paintComponent(Graphics g)
  {
    super.paintComponent(g); 
    if (image != null)
      g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
  }
}    

如何在我的 JFrame 上添加和绘制该面板?我正在尝试将它添加到 mainPanel 但我什至不知道它是否有效.我如何调用或者在哪里调用 paintComponent 方法?

How do I add and draw that panel on my JFrame? I'm trying to add it to the mainPanel but I don't even know if it's working. How can I call or where is the paintComponent method being called?

bgPanel = new BackgroundPanel();
bgPanel.setOpaque(false);
mainPanel.add(bgPanel, new java.awt.GridBagConstraints());    

推荐答案

BackgroundPanel 应该返回图像的尺寸作为最小首选尺寸 (@Override .. getPreferredSize()代码>).如果有组件,可能会更大(超级尺寸更大).

BackgroundPanel should return the size of the image as the minimum preferred size (@Override .. getPreferredSize()). Possibly larger if it has components (the super size is larger).

带有图像的 JLabel 将不起作用,因为我将在背景面板顶部添加不同的标签.

A JLabel with an image won't work because I'm going to be adding different labels on top of the background panel.

有趣的是你应该提到这一点.可以(不一定推荐)设置 JLabel 的布局,然后向其中添加其他 JComponent 对象.在任何 JPanel 对象上调用 setOpaque(false) 很重要,否则 BG 图像将无法显示.

Funny you should mention that. It is possible (not necessarily recommended) to set the layout of a JLabel, then add other JComponent objects to it. It is important to call setOpaque(false) on any JPanel objects or the BG image won't show through.

这演示了两种方法.

import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class BackGroundImage {

    private JComponent ui = null;

    BackGroundImage() {
        initUI();
    }

    public void initUI() {
        if (ui != null) {
            return;
        }

        ui = new JPanel(new GridLayout(0, 1));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        try {
            BufferedImage bi1 = ImageIO.read(
                    new URL ("http://i.stack.imgur.com/OVOg3.jpg"));
            BackgroundPanel bp = new BackgroundPanel(bi1);
            ui.add(bp);
            bp.setLayout(new GridBagLayout());
            JLabel l1 = new JLabel("Using BackgroundPanel");
            Font f = l1.getFont();
            l1.setFont(f.deriveFont(32f));
            l1.setForeground(Color.RED);
            bp.add(l1);
            BufferedImage bi2 = ImageIO.read(
                    new URL ("http://i.stack.imgur.com/lxthA.jpg"));
            JLabel l = new JLabel(new ImageIcon(bi2));
            ui.add(l);
            l.setLayout(new GridBagLayout());
            JLabel l2 = new JLabel("Using JLabel");
            l2.setFont(f.deriveFont(32f));
            l2.setForeground(Color.RED);
            l.add(l2);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                BackGroundImage o = new BackGroundImage();

                JFrame f = new JFrame("BackgroundPanel");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

class BackgroundPanel extends JPanel {

    BufferedImage image;

    public BackgroundPanel(BufferedImage image) {
        this.image = image;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension d = super.getPreferredSize();

        int w = d.width > image.getWidth() ? d.width : image.getWidth();
        int h = d.height > image.getHeight() ? d.height : image.getHeight();

        return new Dimension(w, h);
    }
}

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

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