public class main extends JFrame {
JPanel panel = new JPanel();
JButton playGame = new JButton("PLAY GAME");
public void paint(java.awt.Graphics g) {
super.paint(g);
BufferedImage image = null;
try {
image = ImageIO.read(new File("./src/Images/menu.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(image, 0, 0, 1000, 600, this);
}
public main(){
super();
playGame.setBounds(390, 250, 220, 30);
//panel.setBounds(80, 800, 200, 100);
panel.setLayout(null);
panel.add(playGame);
add(panel);
setTitle("MENU");
setSize(1000,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
//setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String[] args) {
new main();
}
}
我正在尝试将JButton
添加到图像上,但它正在图像后面。
问题是我不知道如何添加背景图片,以便按钮出现在图片的顶部。有没有为我设置背景图片,以便其他面板也显示在顶部?
答案 0 :(得分:0)
尝试将您的背景图片添加到面板中,并且不要从src文件夹加载图像,因为编译后的类将在bin文件夹中创建,因此请使用class.getResource(),它会为您提供相对URL你的形象;另外一件事你永远不应该覆盖JFrame paint方法,因为JFrame上的绘画也应用于框架边框,所以总是尝试通过覆盖JPanel类的paintComponent方法在框架内的面板上绘制:
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class main extends JFrame
{
JButton playGame = new JButton("PLAY GAME");
JPanel panel = new JPanel()
{
public void paintComponent(java.awt.Graphics g)
{
super.paintComponent(g);
BufferedImage image = null;
try
{
image = ImageIO.read(main.class.getResource("/Images/menu.jpg"));
}
catch (IOException e)
{
e.printStackTrace();
}
g.drawImage(image, 0, 0, 1000, 600, this);
}
};
public main()
{
super();
playGame.setBounds(390, 250, 220, 30);
// panel.setBounds(80, 800, 200, 100);
panel.setLayout(null);
panel.add(playGame);
add(panel);
setTitle("MENU");
setSize(1000, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
// setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String[] args)
{
new main();
}
}