将图像设置为 JPanel 背景的最简单方法 [英] Simplest way to set image as JPanel background

查看:42
本文介绍了将图像设置为 JPanel 背景的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不创建新类或方法的情况下将背景图像添加到我的 JPanel 中,而只需将其与 JPanel 的其余属性一起插入?

我正在尝试使用图像设置 JPanel 的背景,但是,我发现的每个示例似乎都建议使用自己的类扩展面板.

我一直在寻找一种方法来简单地添加图像,而无需创建一个全新的类并使用相同的方法(试图使事情井井有条且简单).

这是设置我的 JPanel 的方法示例:

public static JPanel drawGamePanel(){//创建游戏面板和属性JPanel gamePanel = new JPanel();图像背景 = Toolkit.getDefaultToolkit().createImage("Background.png");gamePanel.drawImage(background, 0, 0, null);//设置返回返回游戏面板;}

解决方案

我正在尝试使用图像设置 JPanel 的背景,但是,我发现的每个示例似乎都建议使用自己的类扩展面板

是的,您必须扩展 JPanel 并覆盖 paintcomponent(Graphics g) 函数才能这样做.

@Override受保护的无效paintComponent(图形g){super.paintComponent(g);g.drawImage(bgImage, 0, 0, null);}

<块引用>

我一直在寻找一种方法来简单地添加图像,而无需在相同的方法中创建一个全新的类(尽量使事情井井有条).

您可以使用其他允许直接将图像添加为图标的组件,例如JLabel 如果需要.

ImageIcon icon = new ImageIcon(imgURL);JLabel 拇指 = 新 JLabel();拇指.setIcon(icon);

但再次在括号中尽量让事情井井有条!是什么让你认为仅仅创建一个新类就会导致你进入一个混乱的世界?

How would I add the backgroung image to my JPanel without creating a new class or method, but simply by inserting it along with the rest of the JPanel's attributes?

I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class.

I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).

Here is an example of the method that sets my JPanel:

public static JPanel drawGamePanel(){
    //Create game panel and attributes
    JPanel gamePanel = new JPanel();
    Image background = Toolkit.getDefaultToolkit().createImage("Background.png");
    gamePanel.drawImage(background, 0, 0, null);
    //Set Return
    return gamePanel;
}

解决方案

I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class

yes you will have to extend JPanel and override the paintcomponent(Graphics g) function to do so.

@Override
  protected void paintComponent(Graphics g) {

    super.paintComponent(g);
        g.drawImage(bgImage, 0, 0, null);
}

I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).

You can use other component which allows to add image as icon directly e.g. JLabel if you want.

ImageIcon icon = new ImageIcon(imgURL); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?

这篇关于将图像设置为 JPanel 背景的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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