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

    Dimension size = new Dimension(img.getWidth(null), img.getHeight(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 :


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)

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.

Need Your Help

bundle exec rake db:migrate >> ROUTING ERROR

ruby-on-rails routing bundle ruby-on-rails-3.2 dbmigrate

I got a small problem. I'm new and reading through the guides on how to build a demo_app. I started with '$ rails generate scaffold User name:string email:string' After successfully generating ...

PHP array: orderID with multiple orderdetailIDs

php arrays angularjs

After receiving data from my db I put this data in an array row by row so I can access this array with al the required data later on. But I'm currently using following array:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.