I'm having difficulty with the JTextField and JLabel not appearing with an image in the background of my JFrame. I've set the opacities to false using .setOpaque(false); but it is not working. Thanks for the help in advance.
package Game;
import javax.swing.*;
//window
public class Frame {
public void window(){//window method
JPanel jp = new JPanel();
JLabel jl = new JLabel("Enter a Letter");
JTextField tf = new JTextField(10);
jl.setOpaque(false);
jl.setBorder(null);
jp.add(jl);
jp.add(tf);
LoadImageApp i = new LoadImageApp();
i.setOpaque(false);
JFrame gameFrame = new JFrame();//declaration
gameFrame.getContentPane().add(jp);
gameFrame.add(i);//adds image to window
gameFrame.setTitle("Hangman");//title of frame window
gameFrame.setSize(850, 600);//set size of frame
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when 'x' button pressed
gameFrame.setIconImage(new ImageIcon("Hangman-Game-grey.png").getImage());//set the frame icon to an image loaded from a file
gameFrame.setLocationRelativeTo(null);//window centered over null(center)
gameFrame.setResizable(false);
//gameFrame.getContentPane().setBackground(Color.WHITE);
gameFrame.setVisible(true);//display frame
}
}
package Game;
//import statements
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class LoadImageApp extends JPanel{
private static final long serialVersionUID = 1L;
private ImageIcon image;
public void paintComponent (Graphics g){
super.paintComponent(g);
image = new ImageIcon("hangman.png");
image.paintIcon(this, g, 0, 9);
}
}
package Game;
//main class
public class GameMain {
public static void main (String []args){
Frame frame = new Frame();//declaration
frame.window();//window call
}
}
gameFrame.getContentPane().add(jp);
gameFrame.add(i);//adds image to window
The above code should be something like:
gameFrame.add(i); //adds background image to window
i.add( jp ); // add panel containing label to background image panel
Also, you should NOT be doing I/O in any painting method. Painting methods can be called whenever Swing determines a component needs to be repainted. The image should be read when the class is created.