Search code examples
javajframejbutton

Put JButton over JLabel in a specific spot?


I am fairly new to JFrame and I'm trying to make a game and am stuck on the game menu. I have a background image and would like to place a button over top on a specific spot on the image. I tried putting the jlabel and jbutton in different jpanels and it doesn't help if anything it makes it worse.

This is my current code.

    import java.awt.BorderLayout;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.WindowConstants;

    public class JavaApplication1 {

public static void main(String[] args) throws IOException {
    JFrame myFrame = new JFrame("Memory Game");
    myFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    ImageIcon ii = new                 
    ImageIcon("C:\\Users\\Nancy\\Desktop\\Game\\start_pg.png");
    JLabel img = new JLabel(ii);

    JPanel image = new JPanel();

    ImageIcon btn = new 
    ImageIcon("C:\\Users\\Nancy\\Desktop\\Game\\start_btn.png");
    JButton srt_btn = new JButton(btn);
    srt_btn.setSize(140, 75);
    srt_btn.setOpaque(false);
    srt_btn.setContentAreaFilled(false);
    srt_btn.setBorderPainted(false);
    srt_btn.setBorder(null);

    img.add(BorderLayout.SOUTH, srt_btn);
    image.add(BorderLayout.NORTH, img);


    myFrame.add(image);
    myFrame.pack();
    myFrame.setVisible(true);
}
}

Solution

  • I found the solution, and it was using: button.setLocation(x,y) thanks :)