JButton is drawing behind an image

2019-09-02 06:15发布

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.

3条回答
Bombasti
2楼-- · 2019-09-02 06:17

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.

查看更多
叛逆
3楼-- · 2019-09-02 06:35

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.

查看更多
smile是对你的礼貌
4楼-- · 2019-09-02 06:37

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.

查看更多
登录 后发表回答