在 Java Swing 中向 JFrame 添加背景
adding background to JFrame in Java Swing
我想在 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);
}
}
我尝试了另一个示例,但没有成功!
您目前正在做的是简单地创建一个新的 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();
}
}
这将有效地创建一个具有标签和背景的新框架,然后您可以向其中添加新元素。
使用它应该可以实现您想要实现的目标。
我想在 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);
}
}
我尝试了另一个示例,但没有成功!
您目前正在做的是简单地创建一个新的 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();
}
}
这将有效地创建一个具有标签和背景的新框架,然后您可以向其中添加新元素。
使用它应该可以实现您想要实现的目标。