thegamer
thegamer

Reputation: 57

java gui image problem : doesn't display in the background

i have a query about why is my image not being displayed in my background of my program. I mean i did all the steps necessary and still it would'nt be displayed. The code runs perfectly but without having the image displayed. The directory is written in the good location of the image. I am using java with gui. If anyone could help me solve my problem, i would appreciate :) here is the code below:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*;

public class hehe extends JPanel{

    public hehe(){

            setOpaque(false);
            setLayout(new FlowLayout()); 
          }

    public static void main (String args[]){
           JFrame win = new JFrame("yooooo"); // it is automaticcally hidden

           JPanel mainPanel = new JPanel(new BorderLayout()); 
                win.add(mainPanel);

     JLabel titleLabel = new JLabel("title boss"); 
           titleLabel.setFont(new Font("Arial",Font.BOLD,18)); 
           titleLabel.setForeground(Color.blue);
           mainPanel.add(titleLabel,BorderLayout.NORTH);

           win.setSize(382,269); // the dimensions of the image
           win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           win.setVisible(true);
        }


            public void paint(Graphics g) {

                      Image a = Toolkit.getDefaultToolkit().getImage("C:\\Users\\andrea\\Desktop\\Gui\\car"); // car is the name of the image file and is in JPEG
                g.drawImage(a,0,0,getSize().width,getSize().height,this);
                super.paint(g);
            }
            }

Upvotes: 1

Views: 1095

Answers (2)

Greg McGowan
Greg McGowan

Reputation: 1360

In the code you have provided there is no reference to the hehe class in your main() method. I am guessing you would want to create that object and add it to your window.

Also you would need to include the .jpg extension in the file name

Upvotes: 1

StanislavL
StanislavL

Reputation: 57381

super.paint() draws background after painting your image and your image is hidden. Try to setOpaque(false) or change the order call super.paint() before painting image.

Also avoid obtaining image in paint() method. Paint is called very often so you read your image every time on paint(). Create a field for the image and read it once on creation.

Upvotes: 1

Related Questions