How can I set an image for background of GUI interface?
- by enriched
hey everyone, im having some troubles displaying the background image for a GUI interface in java. Here is what i have at the moment, and with current stage of code it shows default(gray) background.
import javax.swing.*;
import java.awt.event.*;
import java.util.Scanner;
import java.awt.*;
import java.io.File;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
//////////////////////////////////
// 3nriched Games Presents: //
// MIPS The Mouse!! //
//////////////////////////////////
public class mipsMouseGUI extends JFrame implements ActionListener
{
private static String ThePDub = ("mouse"); //the password
JPasswordField pass;
JPanel panel;
JButton btnEnter;
JLabel lblpdub;
public mipsMouseGUI()
{
BufferedImage image = null;
try
{
//attempts to read picture from the folder
image = ImageIO.read(getClass().getResource("/mousepics/mousepic.png"));
}
catch (IOException e)
{
//catches exceptions
e.printStackTrace();
}
ImagePanel panel = new ImagePanel(new ImageIcon("/mousepics/neonglowOnwill.png").getImage());
setIconImage(image);
//sets icon picture
setTitle("Mips The Mouse Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pass = new JPasswordField(5); //sets password length to 5
pass.setEchoChar('@'); //hide characters as @ symbol
pass.addActionListener(this); //adds action listener
add(panel); //adds panel to frame
btnEnter = new JButton("Enter"); //creates a button
btnEnter.addActionListener(this);// Register the action listener.
lblpdub = new JLabel(" Your Password: "); // label that says enter password
panel.add(lblpdub, BorderLayout.CENTER);// adds label and inputbox
panel.add(pass, BorderLayout.CENTER); // to panel and sets location
panel.add(btnEnter, BorderLayout.CENTER); //adds button to panel
pack(); // packs controls and
setLocationRelativeTo(null); // Implicit "this" if inside JFrame constructor.
setVisible(true);// makes them visible (duh)
}
public void actionPerformed(ActionEvent a)
{
Object source = a.getSource();
//char array that holds password
char[] passy = pass.getPassword();
//characters array to string
String p = new String(passy);
//determines if user entered correct password
if(p.equals(ThePDub))
{
JOptionPane.showMessageDialog(null, "Welcome beta user: USERNAME.");
}
else
JOptionPane.showMessageDialog(null, "You have enter an incorrect password. Please try again.");
}
public class ImagePanel extends JPanel
{
private BufferedImage img;
public ImagePanel(String img)
{
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img)
{
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
}
public void paintComponent(Graphics g)
{
g.drawImage(img, 0, 0, null);
}
}
}