0

This is my code, the program complies there is nothing wrong with the code but I don't why the image doesn't show on the frame. I imported most of the classes since at the beginning the code had a compilation error. I want to add an image to the whole frame. A background image basically. Also how can I add an image to panel 1 if I wanted to?

import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.util.*;
import java.lang.*;


public class Class extends JFrame{

  public Class(){
  JPanel p1 = new JPanel(null);
  JPanel p2 = new JPanel();


 JButton jbt = new JButton("More Info");
 JButton jbt2 = new JButton("Play Game");


  p1.setBorder(new TitledBorder("Challenge"));
  p2.setBorder(new TitledBorder("Instruction: \n"));

  p2.add(jbt,BorderLayout.SOUTH);
  p2.add(jbt2,BorderLayout.SOUTH);
  p2.setBounds(1000, 570, 250, 90);
  p1.add(p2);
  add(p1);
}
Image image;
public void ImagePanel() {
   try {                
      image = ImageIO.read(new File("background.jpg"));
   } catch (IOException ex) {
        System.out.println("No image");
   }
}

public void paintComponent(Graphics g) {

    g.drawImage(image, 0, 0, null);         
}

public static void main(String[] args) {
    Class frame = new Class(); 
    frame.setTitle("Title");
    frame.setSize(1900, 1200); 
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}


 }
R.Mash
  • 1
  • 1
  • Have you tested your code to see that your image File is being read in properly? Is the image null? You shouldn't be using File here but rather class resource. Side note: you're not calling the super's paintComponent method, a dangerous thing to omit. – Hovercraft Full Of Eels Nov 22 '15 at 19:00
  • The main problem with you code is that JFrame does not have a paintComponent() method so your painting logic never gets invoked. Any time you attempt override a method don't forget the `@Override` statement before the method then the compiler will point out this error. In any case you should not be attempting to override the painting method of a JFrame. – camickr Nov 22 '15 at 19:05

0 Answers0