问题描述
我想在 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,200,200);
frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1080,720);
frame.setLayout(null);
frame.setResizable(false);
frame.setVisible(true);
frame.setContentPane(background);
}
}
我尝试了另一个示例,但没有奏效!
解决方法
您当前所做的只是创建一个新的 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();
}
}
这将有效地创建一个带有背景标签的新框架,然后您可以向其添加新元素。
使用它应该可以完成您想要实现的目标。