I have a program that's essentially supposed to be a title screen for a few games. The background is a GIF (I'm not sure if that's contributing to the problem), and I need to have some JButtons
that allow for me to run the actual games. The problem is that the JButton
only shows up sometimes when I hover over it (and for a split second, at that), otherwise it's invisible. It works just fine, goes to the game and all, it's just invisible.
I've tried to see if the problem is the fact that I'm using a GIF, as well as the paintComponent()
method, although, it just didn't show up when I used a JPEG.
Here's the code:
public class TestingGrounds extends JFrame{
//declarations
JButton snakeButton;
JPanel snakeButtonPanel;
JFrame window;
Container con;
TitleScreenHandler tsHandler = new TitleScreenHandler();
//constructor
public TestingGrounds(){
//main JFrame
window = new JFrame("Title Screen");
window.add(new ImagePanel());
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(1831, 1030);
window.setVisible(true);
window.setLocationRelativeTo(null);
window.setLayout(null);
con = window.getContentPane();
//panel for the button to go to the snake game
snakeButtonPanel = new JPanel();
snakeButtonPanel.setBounds(100,100,600,150);
//button to go to snake game
snakeButton = new JButton("Snake");
snakeButton.setBackground(Color.BLACK);
snakeButton.setForeground(Color.WHITE);
snakeButton.setFont(new Font("Times New Roman", Font.ITALIC, 30));
snakeButton.addActionListener(tsHandler);
snakeButton.setFocusPainted(false);
//adding button to panel
snakeButtonPanel.add(snakeButton);
//adding panel to container
con.add(snakeButtonPanel);
//setting the panel as visible
snakeButtonPanel.setVisible(true);
}
//main method for running constructor
public static void main(String[] args) {
new TestingGrounds();
}
//what to do if the button is pressed
public class TitleScreenHandler implements ActionListener {
public void actionPerformed(ActionEvent event){
//goes to main game screen if start button is pressed
new SnakeGame();
}
}
}
//class for using the gif
class ImagePanel extends JPanel {
Image image;
public ImagePanel() {
image = Toolkit.getDefaultToolkit().createImage("C:/Users/eklut/Desktop/Coding/ICS4U1/src/graphicsstuff/snek/source.gif");
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
Sorry, I know it's a fair amount of code, but I feel like I have to show all of it as I'm not exactly sure where the problem stems from.
I expected the button to show up over the gif, but it almost seems like it's happening the other way around