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