2 qq 30941763 qq_30941763 于 2017.08.27 11:31 提问

java中panel的背景图片总是挡住按钮怎么解决?

package ShootGame;

import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ShootGame extends JFrame
{
GamePanel jp;
JButton beginButton;
JButton settingsButton;
JButton helpButton;

public static BufferedImage startBackGound;
static
{
try {
startBackGound=ImageIO.read(ShootGame.class.getResource("startBackGround.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ShootGame()
{
super("飞机大战");
setSize(1920,821);
jp=new GamePanel();
getContentPane().add(jp);

beginButton=new JButton("开始游戏");
settingsButton=new JButton("设置");
helpButton=new JButton("帮助");

jp.add(beginButton);
jp.add(settingsButton);
jp.add(helpButton);

beginButton.setBounds(500,500,100,20);
settingsButton.setBounds(500,530,100,20);
helpButton.setBounds(500,560,100,20);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

class GamePanel extends JPanel
{
GamePanel()
{
setLayout(null);
}
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.drawImage(startBackGound, 0, 0, null);
}
}
public static void main(String[] args)
{
new ShootGame();
}
}

2个回答

qq_19865749
qq_19865749   2017.08.27 13:06
已采纳

你只需记住一点,每次都是重绘整个组件,所以你paint方法中应该绘制了背景图片后,还要绘制里面包含的按钮等组件。此外,鼠标覆盖、菜单弹窗
等直接影响到该组件显示的行为都会自动触发该组件的repaint 方法,而repaint最终调用paint,所以paint 中必须每次都绘制完整的显示信息。

zy841958835
zy841958835   Ds   Rxr 2017.08.27 12:22

先 g.drawImage(startBackGound, 0, 0, null);

Csdn user default icon
上传中...
上传图片
插入图片