arunptl100
arunptl100

Reputation: 15

Image not loading/updating

Here is the code for this program. If i load the images in public void paintComponent(Graphics g) {} method the images load , however if i load them from another class they do not.

main class:

public class main {

    static GUI GUI = new GUI();
    static render render = new render();
    static loader loader = new loader();

    public static void main(String [] args) {
        frame.start();
        loader.start();

    }
}

frame class:

public class GUI implements Runnable {

    public void start() {
        new Thread(this).start();
    }

    public void run(){ 
        JFrame frame = new JFrame(); 
        System.out.println("frame starting");
        frame.setSize(700,600); 
        frame.setResizable(false); 
        frame.setLocationRelativeTo(null);
        frame.setTitle("Project ");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        frame.addMouseListener(render);
        frame.add(render);
        frame.setVisible(true);
    }
}

render class

public class render extends JPanel implements ActionListener {

    Timer tm = new Timer(7, this);
    loader loader = new loader();

    public render() {
        tm.start();
    }

    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(loader.Getbackground(), -100,-400,null);

    public void actionPerformed(ActionEvent e) {
        repaint();
    }
}

loader class

public class loader implements Runnable {

    Image background;

    public void start() {
        new Thread(this).start();
    }

    public void run() {
        ImageIcon backgroundhold = new ImageIcon(render.class.getResource("resources/Background.png"));
        background = backgroundhold.getImage();
        setbackground(background);
    }

    public void setbackground(Image background) {
        this.background = background;

    }

    public Image Getbackground() {
        return background;
    }

    public void setbackground(Image background){
        this.background = background;

    }
}

When the program starts it opens an empty frame with no images. What am I doing wrong?

Arun

Upvotes: 0

Views: 35

Answers (1)

MCHAppy
MCHAppy

Reputation: 1002

Notice that paint programs SHOULD override paintComponent() to draw/load/... images

So if you want to load images in another class , it should extends Jpanel and override paintComponent() like you did with render class .

Upvotes: 1

Related Questions