【问题标题】:Java won't draw my image when method is called using threads使用线程调用方法时,Java 不会绘制我的图像
【发布时间】:2012-10-18 08:03:45
【问题描述】:

我有这个花程序,它应该从上面放花....我需要它等待几秒钟,然后调用方法来放花。我知道该方法运行,因为我让它打印出下降的 y 值。但它不会在屏幕上绘制它。我真的不知道我做错了什么。这是一些代码...

    //Ignore starting here
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.Random;
    //Ignore ending here

    public class RedFlower implements ActionListener{
        Timer time;
        ImageIcon i = new ImageIcon("graphics//flowers//red_flower.png");
        Image flower = i.getImage();
        int y, x;
        int dy = 1;
        public void dropFlower(){
            Random rnd = new Random();
            y = 50;
            x = rnd.nextInt(1216);
            time = new Timer(5, this);
            time.start();
}
public void actionPerformed(ActionEvent e){// used for stoping the timer when off the screen
    int checky = y++;
    if(checky < 720){
        y++;
    }else{
        time.stop();
    }
    System.out.println(y);

}
//everything after this is what i call in the other method
    public Image getImage(){
    return flower;
}
public int getX(){
    return x;
}
public int getY(){
    return y;
}
    }

现在这是我的绘图代码...

    public void paintComponent(java.awt.Graphics g){
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;

    g2d.drawImage(rf.getImage(), rf.getX(), rf.getY(), null);// rf is what i called the method
    g2d.drawImage(sc.getImage(), sc.getX(), sc.getY(), null);//this is the basket that you control
}

还有一个奇怪的事情是当我按下按钮调用它工作的方法但不是当线程运行它时......

【问题讨论】:

  • 您的 actionPerformed 方法什么都不做,它在您按下按钮时起作用的原因是因为按钮事件会导致您的框架更新和重新绘制。尝试将your_component.repaint(); 添加到y++; 下方的actionPreformed 方法中
  • 1) g2d.drawImage(rf.getImage(), rf.getX(), rf.getY(), null); 应该是 g2d.drawImage(rf.getImage(), rf.getX(), rf.getY(), this); 2) 为了尽快获得更好的帮助,请发布 SSCCE。
  • ImageIcon i = new ImageIcon("graphics//flowers//red_flower.png"); Uggh.. 1) 不需要//(在任何系统上),Windows 会理解/。 2) 如果路径错误,ImageIcon 会静默失败。使用ImageIO。 3) 虽然这可能会在您的 IDE 中工作(将图像加载为 File),但在部署时它不会工作。使用 Class.getResource("/path/to/image") 获取 URL。
  • 每 5 毫秒更新一次是多余的,你也可能没有给重绘管理器和 EDT 时间来真正呼吸。您的动画以 200 fps 的速度更新...尝试更接近 40/100 毫秒的速度(在其他一切之上)

标签: java multithreading image graphics awt


【解决方案1】:

去掉双斜线。

 ImageIcon i = new ImageIcon("graphics/flowers/red_flower.png");

【讨论】:

  • 我怀疑这会产生任何影响(尽管应该更改),请参阅我的第二条评论。
猜你喜欢
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多