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添加到图像上,但它位于图像的后面。
问题是我不知道如何添加背景图片,使按钮出现在图片的顶部。有没有为我设置背景图片,以便其他面板也显示在顶部的方法?
发布于 2014-11-16 19:09:09
尝试将你的背景图片添加到你的面板中,并且不要从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();
}
}https://stackoverflow.com/questions/26955366
复制相似问题