JButton正在绘制一幅图像 [英] JButton is drawing behind an image
问题描述
我正在制作一个起始屏幕,它正在运行得非常好,在启动时得到一个背景图像,现在我正在尝试在startmenu上绘制一个JButton,这是一个JFrame。但是当我运行程序时,按钮出现在背景图片后面。如果我将鼠标悬停在放置按钮的区域上方,则会闪烁,当我点击它时也会发生这种情况。有没有办法画出背景的按钮INFRONT?我在代码中将按钮作为最后一个。我的代码用于绘制背景和按钮:
I am making a starting screen, and it's working out pretty fine, got a background image when it starts, now I am trying to draw a JButton on the startmenu, which is a JFrame. But when I run my program, the button appears behind the background picture. If I hover above the area where the button is placed, it's flickering, and when I click it that happens too. Is there any way to draw the Button INFRONT of the background? I made the button as last in the code. My code to draw the background and button:
public void drawStartScreen(){
startScreenOn = true;
Graphics2D b = buffer.createGraphics();
b.setColor( Color.WHITE );
b.fillRect(0, 0, 800, 600);
b.drawImage(start,0,0,null);
setLayout( null );
button = new JButton("Start Game");
button.setBounds(10,10,100,100);
button.setVisible( true );
add(button);
}
它首先绘制图像,然后是Button,但按钮仍然绘制图像背后。
It draws the image first, and then the Button, but the button still draws behind the image.
推荐答案
覆盖JFrame上的paint方法:
Override the paint method on the JFrame:
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D b = (Graphics2D)g;
b.setColor( Color.WHITE );
b.fillRect(0, 0, 800, 600);
b.drawImage(start.getImage(),0,0,null);
b.dispose();
}
请注意,这会调用 paint()$完成后,在图形上下文中对父级和
dispose()
执行c $ c>。我刚尝试了这段代码,它对我有用。
Notice that this calls paint()
on the parent and dispose()
on the graphics context when done. I just tried this code and it worked for me.
这篇关于JButton正在绘制一幅图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!