图像未加载/更新

时间:2014-05-17 13:32:31

标签: java image

以下是此计划的代码。如果我在public void paintComponent(Graphics g){}方法中加载图像,则加载图像,但是如果我从另一个类中加载它们则不加载它们。

主要课程:

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();

    }
}

框架类:

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);
    }
}

渲染类

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();
    }
}

加载器类

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;

    }
}

程序启动时会打开一个没有图像的空框。我做错了什么?

阿伦

1 个答案:

答案 0 :(得分:0)

请注意,绘图程序SHOULD会覆盖paintComponent()以绘制/加载/ ...图像

因此,如果您想在另一个类中加载图像,它应该扩展Jpanel并覆盖paintComponent(),就像使用渲染类一样。