简体   繁体   中英

How to add JPanel Components on top of a painted background

I want to be able to change one of my JPanel background to a image I created and still add components on top of it, however they are not showing up.

package userInterface;

import javax.swing.*;
import java.awt.*;

@SuppressWarnings("serial") public class BoardPanel extends JPanel {

  private Image img;

  public BoardPanel() {
    img = new ImageIcon("images/board.png").getImage();
    JButton button = new JButton("TEST ME");
    add(button);

    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
  }

  public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, null);
  }

}

If you overwrite paintComponent(Graphics g) , always remember to call super.paintComponent(g) first. That way everything which would normally be painted will be painted as well.

The reason for non-visibility of JButton on the JPanel is that you are setting the layout of the JPanel to be null :

setLayout(null);

Setting layout to be null makes you to set the location of the components explicitly which is also very bad practice. You should instead remove that line and let the internal layout of the Swing to do its work gracefully.
As side note I would emphasize on the point that whenever you are overriding the paintComponent method , the first statement of this method must be super.paintComponent(g)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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