我使用一个图像作为背景,然后我有另一个图像作为 JButton。背景图像当前与按钮重叠,因此您看不到它。当我注释掉 repaint() 时,按钮在前面,但是因为我重新定位了按钮,所以该空间从背景图像中淡出。所以基本上,我必须如何处理我的代码才能将按钮放在背景图像前面(背景图像仍然完好无损)?
public class Start extends JFrame {
JPanel jp = new JPanel();
JButton startButton = new JButton();
private Image dbImage;
private Graphics dbg;
Image backgroundFirst;
int backx;
int backy;
public Start() {
ImageIcon i = new ImageIcon(
"C:/Users/Mel/workspace/camptycoon/javagame/src/javagame/background1.png");
backgroundFirst = i.getImage();
startButton
.setIcon(new ImageIcon(
"C:/Users/Mel/workspace/camptycoon/javagame/src/javagame/start.png"));
jp.add(startButton);
startButton.setLayout(getLayout());
add(jp);
validate();
// Frame Properties
setTitle("Counselor Training");
setVisible(true);
setSize(755, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public LayoutManager getLayout() {
int x = 540;
int y = 475;
startButton.setLocation(x, y);
startButton.setBorder(null);
return null;
}
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
backx = 10;
backy = 30;
g.setColor(Color.BLUE);
g.drawImage(backgroundFirst, backx, backy, this);
//repaint();
}
}