开发者

JButton is drawing behind an image

开发者 https://www.devze.com 2023-02-24 19:39 出处:网络
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开发者_StackOverflow社区 draw a JButton on the startmenu, which is a JFrame.

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开发者_StackOverflow社区 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.


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.


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 a JFrame that has multiple layers.


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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号