将ImageIcon从对象内部添加到另一个类中的帧

时间:2016-03-27 15:22:40

标签: java swing user-interface

public class Dog {

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        ImageIcon image = new ImageIcon("dog.jpg");
        image.paintIcon(this,g,200,0);
    }

    public class Gui extends JFrame {
        Frame frame = new Frame();
        Dog dog = new Dog();
        frame.add(dog.paintComponent(??));
    }
}

因此dog对象中paint组件的方法将被添加到JFrame或JPanel中。

这是正确的方法,还是需要调用repaint()函数?

1 个答案:

答案 0 :(得分:0)

  

这是正确的解决方法,还是需要调用repaint()函数

不幸的是,这不是正确的方法。 paintComponent(g)应该被覆盖。您需要将Dog类扩展为JComponent或JComponent的子类之一,然后重写paintComponent(g)

class Dog extends JComponent{
    @Override
    paintComponent(Graphics g){
        //your codes..
    } 
}

但是,如果您只想创建可以使用自定义绘制绘制的Dog对象,则无需使用paintComponent()方法。您只需为它创建一个draw()方法:

class Dog{

    private ImageIcon image;

    public Dog(){
        java.net.URL imgUrl = getClass().getResource("dog.jpg");
        image= new ImageIcon(imgUrl);
    }

    public void draw(Graphics g){
        g.drawImage(image.getImage(), x, y, width, height, null);
    }

}

如果您想在画布或面板中绘制 Dog

public class DrawingSpace extends JPanel
{
    private Dog dog;

    public DrawingSpace(){
        dog = new Dog();
    }

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        dog.draw(g);   //will invoke Dog's draw method and draw a dog
    }
}