在javaswing中为jframe添加背景

lf3rwulv  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(270)

这个问题在这里已经有了答案

将java中的标签设置为图像格式问题(1个答案)
5天前关门了。
我想在jframe的背景上设置一个图像,但我不能。这是代码:

import javax.swing.*;
import java.awt.*;

public class Main {

public static void main(String[] args) {

    ImageIcon image = new ImageIcon("pic.png");
    JFrame frame = new JFrame();

    JLabel background = new JLabel();
    background.setIcon(image);
    background.setBounds(0 , 0 , 200 , 200);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1080, 720);
    frame.setLayout(null);
        frame.setResizable(false);
        frame.setVisible(true);
        frame.setContentPane(background);
    }
}

我尝试了另一个例子,但没有工作!

kxe2p93d

kxe2p93d1#

你现在所做的只是创建一个新的 JLabel 对象(即 background )向其中添加图像对象。
这不会达到你想要达到的目标。不幸的是,没有现成的方法将图像作为背景添加到 JFrame 但你可以很容易地尝试:

public class BackGroundFrame extends JFrame {

    public BackGroundFrame() {
        setSize(400, 400);
        setVisible(true);
        setLayout(new BorderLayout());
        JLabel background = new JLabel(new ImageIcon("C:\\tmp\\test.jpg"));
        add(background);
        background.setLayout(new FlowLayout());
        background.add(new JLabel("My Label"));
        background.add(new JButton("My button"));
        revalidate();
    }

    public static void main(String... args) {
        new BackGroundFrame();
    }

}

这将有效地创建一个具有背景的标签的新框架,然后可以向其中添加新元素。
使用这个应该可以完成你想要达到的目标。

相关问题