JButton 正在图像后面绘制
我正在制作一个启动屏幕,它运行得很好,启动时有一个背景图像,现在我试图在开始菜单上绘制一个 JButton,它是一个 JFrame。但是当我运行我的程序时,该按钮出现在背景图片后面。如果我将鼠标悬停在放置按钮的区域上方,它就会闪烁,当我单击它时也会发生这种情况。有什么方法可以绘制背景的Button INFRONT吗?我将按钮设置为代码中的最后一个。我绘制背景和按钮的代码:
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);
}
它首先绘制图像,然后绘制按钮,但按钮仍然绘制在图像后面。
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);
}
It draws the image first, and then the Button, but the button still draws behind the image.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在混合绘画和添加组件,您绝对不应该这样做。相反,当您创建屏幕或第一次需要它们时添加组件,但确保只执行一次。然后在
paintComponent()
方法中单独修改需要绘制更改的组件。You are mixing painting and adding of components and you definitely shouldn't be doing this. Instead add components when you create the screen or when you first need them but make sure you are only doing this once. Then separate modify the components that need painting changes inside the
paintComponent()
method.我建议您使用
JLayeredPane
< /a> (我只将定制绘画作为最后的手段)。如果您仍然有兴趣将“低级”绘画与“高级”
JComponent
层次结构混合在一起,请查看关于具有多个层的JFrame
的问题。I recommend you'd use a
JLayeredPane
(I go for custom painting only as a last resort).If you're still interested in mixing the 'low-level' painting with 'higher-level'
JComponent
hierarchy, look at a question about aJFrame
that has multiple layers.覆盖 JFrame 上的 Paint 方法:
请注意,完成后,这会在父级上调用
paint()
并在图形上下文上调用dispose()
。我刚刚尝试了这段代码,它对我有用。Override the paint method on the JFrame:
Notice that this calls
paint()
on the parent anddispose()
on the graphics context when done. I just tried this code and it worked for me.