简体   繁体   English

JButton正在绘制图像

[英]JButton is drawing behind an image

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. 我正在制作一个起始屏幕,并且工作得很好,启动时得到了背景图像,现在我试图在起始菜单上绘制一个JButton,它是一个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? 有什么办法绘制背景的按钮INFRONT? 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. 它先绘制图像,然后绘制按钮,但是按钮仍在图像后面绘制。

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. 然后单独修改paintComponent()方法中需要绘画更改的组件。

I recommend you'd use a JLayeredPane (I go for custom painting only as a last resort). 我建议您使用JLayeredPane (我只能将自定义绘画用作最后的选择)。

If you're still interested in mixing the 'low-level' painting with 'higher-level' JComponent hierarchy, look at a question about a JFrame that has multiple layers. 如果您仍然有兴趣将“低级”绘画与“高级” JComponent层次结构混合在一起,请查看有关具有多个层的JFrame 的问题

Override the paint method on the JFrame: 覆盖JFrame上的paint方法:

@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();        
}

Notice that this calls paint() on the parent and dispose() on the graphics context when done. 注意,完成后,这将在父对象上调用paint() ,并在图形上下文上调用dispose() I just tried this code and it worked for me. 我只是尝试了这段代码,它为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM