简体   繁体   English

有没有一种方法可以在不使用JLabel或Overrideing paintComponent的情况下向JPanel添加背景图像?

[英]Is there a ways I can add background image to JPanel without using JLabel or Overriding paintComponent?

I want to add background image to JPanel without using JLabel or overriding paintComponent. 我想在不使用JLabel或重写paintComponent的情况下将背景图像添加到JPanel。

JPanel don't have setIcon(ImageIcon). JPanel没有setIcon(ImageIcon)。 I really want to dynamically change the background image of JPanel like setIcon in other component like JLabel. 我真的很想在其他组件(如JLabel)中动态更改JPanel的背景图像(如setIcon)。

"I want to add background image to JPanel without using JLabel or overriding paintComponent" “我想在不使用JLabel或重写paintComponent的情况下将背景图像添加到JPanel”

Seems like a bit of a stretch. 似乎有点舒展。 You want to do something, but you don't to do it the way it's supposed to be done. 您想要做某事,但是不想按照原本应该做的方式去做。 Maybe a better understanding of how this can be accomplished will make you change your mind. 也许对如何实现这一目标的更好理解会使您改变主意。

JPanel and override paintComponent JPanel和重写paintComponent

Have a method to setImage(Image image) or you can use ImageIcon , up to you. 有一个方法来setImage(Image image)或者您可以使用ImageIcon You can set the image that is used to paint the background. 您可以设置用于绘制背景的图像。

public class BackgroundPanel extends JPanel {
    private Image image;

    public void setImage(Image image) {
        this.image = image;
        repaint();
    }

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

When you call setImage passing it an image, it will dynamically change the image, because of the call to repaint() 调用setImage传递图像时,由于调用repaint() ,它将动态更改图像

Using JLabel 使用JLabel

As nIcE cOw mentioned, you can use the JLabel as the container, and add all your components to the label. 正如nICEE所提到的,您可以将JLabel用作容器,并将所有组件添加到标签中。 Remember JLabel is a subclass of Container. 请记住,JLabel是Container的子类。 Any Container can be added to. 可以将任何容器添加到其中。 Just keep in mind that JLabel has no layout manager (unlike JFrame and JPanel which has defaults), so you need to set it. 请记住,JLabel没有布局管理器(与具有默认设置的JFrame和JPanel不同),因此您需要进行设置。 You could simply do something like 你可以简单地做

JLabel backgroundLabel = new JLabel();
backgroundLabel.setIcon(new ImageIcon("backgound.png"));
backgroundLabel.setLayout(new GridBagLayout());
backgroundLabel.add(new JButton("Hello World"));

That's perfectly legal. 那是完全合法的。

Another Alternative 另一种选择

A class from Sir Rob Camick BackgroundPanel . Rob Camick爵士BackgroundPanel先生的一类。 Check out the link for how to use it. 查看链接以了解如何使用它。 It's basically the same concept as the first option I described, just 100 times better with a whole lot more goodies. 它与我所描述的第一个选项基本上是相同的概念,仅比其他选项好100倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM