paintComponent不是在画什么东西?

时间:2014-05-20 09:57:00

标签: java swing actionlistener paintcomponent repaint

我无法使用actionListener和paintComponent绘制任何内容。我很确定我的图像名称/路径是正确的。我做错了什么?

JApplet“Runner.java”

public class Runner extends JApplet{

    public void init(){
        World world = new World();
        Container screen = this.getContentPane();
        screen.add(world);
        setSize(1200, 800);
        repaint();
    }
}

“World.java”的一部分

protected ArrayList<WorldObject> allStillObjects = new ArrayList<WorldObject>();
protected ArrayList<MovableObject> allMovableObjects = new ArrayList<MovableObject>();
protected ArrayList<WorldObject> screenStillObjects = new ArrayList<WorldObject>();
protected ArrayList<MovableObject> screenMovableObjects = new ArrayList<MovableObject>();

public World(){
    this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
    this.setBackground(new Color(255,255,255));
    this.setFocusable(true);
    this.setFocusTraversalKeysEnabled(false);

    this.addObject(new Card(this, "Two of Clubs", 0, 0, "card_two_c.png"));

    timer = new Timer(60, new ClickListener());
    timer.start();
}

public void addObject(WorldObject obj){
    if(obj instanceof MovableObject){
        this.allMovableObjects.add((MovableObject)obj);
        if(isOnScreen(obj))
            this.screenMovableObjects.add((MovableObject)obj);  
    }else{
        this.allStillObjects.add(obj);
        if(isOnScreen(obj))
            this.screenStillObjects.add(obj);
    }
}

public void paintComponent(Graphics g){
    super.paintComponent(g);
    for(WorldObject obj : this.screenStillObjects)
        obj.paintComponent(g);
    for(MovableObject obj : this.screenMovableObjects)
        obj.paintComponent(g);
}

private class ClickListener implements ActionListener{

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

“ImageObject.java”

protected ImageIcon pic;

public ImageObject(World world, String name, int worldX, int worldY, String imageName){
    super(world, name, worldX, worldY);
    URL imgURL = getClass().getResource("images/" + imageName);
    pic = new ImageIcon(imgURL);

    this.width = pic.getIconWidth();
    this.height = pic.getIconHeight();
}

public void paintComponent(Graphics g){
    super.paintComponent(); //doesn't work with or without this line
    pic.paintIcon(world, g, this.getWorldX(), this.getWorldY());
}

如果这里没有足够的代码,我可以添加更多

编辑:使用JApplet的最佳替代方法是什么? World扩展JPanel,WorldObject扩展JPanel,ImageObject扩展WorldObject,MovableObject扩展ImageObject,Card扩展MovableObject

我在上面添加了addObject的方法。

1 个答案:

答案 0 :(得分:0)

非常感谢您的回答,呃,评论!他们非常有帮助。我去改变了我的程序,以便它使用JFrame而不是JApplet,经过一点点摆弄后,得到了一个要打印的图像。从那里我能够恢复到JApplet,它的工作原理!仍然不确定我最初的问题是什么:|