0

Java newbie here... I am trying to add an image to the background of my JFrame. I already had buttons added to the panel, on that JFrame. When I added the image to the JFrame, my buttons disappeared.

public class BackPanel extends JFrame {

JFrame frame = new JFrame("Blackjack Game");

ImageIcon background;
JLabel backgroundLbl;

JButton newRoundButton;
JButton endButton;

ImageIcon image;

public BackPanel(GameConsole game){

    final GameConsole game1 = game;
    frame.setSize(800, 600);
  //frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   

  //frame.setContentPane(new JLabel(new ImageIcon(getClass().getResource("cardBackground.jpg"))));
    ImagePanel panel = new ImagePanel("cardBackground.jpg");
    panel.setPreferredSize(new Dimension(800, 600));



    //put frame in the middle of the screen
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);


    //create 2 buttons on the panel

    panel.add(endButton);
    panel.add(newRoundButton);
    frame.getContentPane().add(panel, BorderLayout.CENTER);   //add the panel to the frame

//  frame.pack();
    frame.setVisible(true);
    }
}

I have a feeling it has something to do with layout, but when I use other layouts it doesn't seem to help, or it also makes the image disappear.

I have changed the file from "cardBackground.jpg" to "" in order to see if the buttons are somehow underneath the image. They are not.

I have tried to widen the frame to see if the buttons are next to the image but they aren't. (Which wouldn't make sense anyways because they are not on the same panel).

What am I missing on this?

EDIT: Updated code that is not working: Displays buttons but no background image.

import java.awt.Dimension;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class BackPanel{

    public BackPanel(GameConsole game){
        final GameConsole game1 = game;

        JFrame frame = new JFrame("Blackjack Game");
        ImagePanel panel = new ImagePanel("cardBackground.jpg");
        panel.setPreferredSize(new Dimension(800, 600));


        //create 2 buttons on the panel
        JButton newRoundButton= new JButton("Start another round");
        newRoundButton.setPreferredSize(new Dimension(150, 50));
        newRoundButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                game1.userTurn();
            }
        });

        JButton endButton = new JButton("End Game");
        endButton.setPreferredSize(new Dimension(150, 50));
        endButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "You have chosen to quit.\n"
                        + "Thank you for playing Blackjack.");
                System.exit(0);
            }
        });

        panel.add(endButton);
        panel.add(newRoundButton);

        frame.add(panel);
        frame.setSize(800, 600);

        frame.setLocationRelativeTo(null);


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        frame.setVisible(true);
        }
    }
L. Morrell
  • 45
  • 10

1 Answers1

0

Instead of adding an image background like this, make a new JPanel class that has an overloaded paintComponent() function where you draw an image. Here is a link that exemplifies this solution:

Adding an Image to a JPanel Background

Happy coding!

Edit:

I whipped up an example in Eclipse and everything worked fine for me. Here is the code I used:

import java.awt.Dimension;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Test {
    public static void main(String[] args) throws IOException {
        JFrame myFrame = new JFrame();

        //Make a background panel
        ImagePanel panel = new ImagePanel("back.jpg");
        panel.setPreferredSize(new Dimension(800, 600));

        //Make buttons
        JButton button1 = new JButton("Button 1");
        JButton button2 = new JButton("Button 2");

        //Add components
        panel.add(button1);
        panel.add(button2);

        myFrame.add(panel);

        //Set window size
        myFrame.setSize(800, 600);

        //Center it
        myFrame.setLocationRelativeTo(null);

        //Make it close normally
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Make it visible (finalization)
        myFrame.setVisible(true);
    }
}

Here is the ImagePanel code from before as well:

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {

    private Image image = null;

    public ImagePanel(String filename) {
        this.image = new ImageIcon(filename).getImage();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
    }
}

And here are the results: http://postimg.org/image/93k3j5f43/

Community
  • 1
  • 1
  • I updated my code, and for my new class it is exactly like the linked page. It didn't look like I needed to change anything. I added the new class, and did as the page suggested (thank you for it), but now my buttons are there and the image is not. Also, is there a reason why this is the preferred way? – L. Morrell Dec 14 '14 at 15:09
  • @learned.beh Oh no! Sorry about that. Hmmmm I would try moving "frame.getContentPane().add(panel, BorderLayout.CENTER);" after the lines "panel.add(newRoundButton);". If I'm not mistaken, you should always add components to JPanel' before adding them other JFrames and JPanels. To answer your other question, I think it's the preferred way because you have a lot more control over your JPanel if you make a custom class. – Casey Warrer Dec 14 '14 at 15:20
  • I moved it to that location. There is no change. No image, but showing the buttons. This way does seem like it would have more control. If I get it to work of course lol – L. Morrell Dec 14 '14 at 15:25
  • Try adding this line of code after you create the ImagePanel: panel.setPreferredSize(new Dimension(800, 600)); – Casey Warrer Dec 14 '14 at 15:32
  • No go. same. I updated the code with the above changes to show you exactly what I have. – L. Morrell Dec 14 '14 at 15:43
  • This is so strange! I think it might be the layout (as you suggested in the original post) but I don't understand why. I'm going to take your code and fiddle around with it until I can get it to work. I will edit my answer once I figure something out. – Casey Warrer Dec 14 '14 at 15:51
  • @learned.beh I edited my original post. I got my code to work as intended. Hopefully you can use it to modify your code and yours will work too! Good luck mate. – Casey Warrer Dec 14 '14 at 17:17
  • For some reason it is still throwing me for a loop. For the Image Panel, I literally have the same class. I updated the code to include the WHOLE BackPanel class, including the ActionListeners for the buttons. Is there any reason that these would interfere with the background? The only difference seems to be that, and the fact that yours is in main(), but I can't imagine that would make a difference. – L. Morrell Dec 14 '14 at 18:27
  • There might be something your JFrame is missing because it isn't inside main() and I agree that shouldn't make a difference but I think it is. For my Java GUI programs, I usually make a class called MainDriver() that contains just main(). I also make a class called MainWindow() that extends JFrame and I make that class into the main GUI window and it handles all the components and adds them to itself by using this.add(*component*);. Back in the MainDriver() program, I instantiate my MainWindow() class and treat it like how you're treating your JFrame but just in main. I hope that helps :( – Casey Warrer Dec 14 '14 at 18:40
  • I just put it all in main() just to see if it would work, and it didn't. Thanks for your valiant effort. I'll try to work around it, and change my vision for this project. Perhaps presenting this stumper in my final project may get me a solution from a classmate. If it does, I'll post it. Thanks again :-) – L. Morrell Dec 15 '14 at 00:23
  • @learned.beh dang! I'm sorry that it's been a stumper. I'm glad I could try to help! Good luck! – Casey Warrer Dec 16 '14 at 04:18