如何使用绘制内容所需的逻辑传递paintComponent和object?

时间:2013-08-28 08:01:30

标签: java swing graphics jframe paintcomponent

所以我实例化了一个带有与该对象相关的2D数据矩阵的对象。我对这个数据矩阵执行了所有逻辑,现在我已经准备好看到这个2D矩阵的视觉效果了。

我想打印一个空矩形的实心矩形,具体取决于矩阵中的值。

这是我在伪代码中遇到的麻烦:

public void paintComponent(Graphics g)
{
    g.setColor(Color.gray);
    g.fillRect(0,0, 500, 500);

    // I need the logic from the instantiated logic from the main method but I cant pass the object into the paintComponent method when I tried. How can I access the objectGrid object from the main method in this method? 

}

public static void main(String[] args) {
    Class newObject = new Class();

    //Do operations on newly instantiated object
    newObject.performOperation;

    // Start a new JFrame object which will call the paintComponent method automatically
    // But I want to pass newObject to paintComponent method and I don't know how to do it

    JFrame window = new JFrame();
    window.setSize(500, 500);
    window.setVisible(true);
}

我希望这是有道理的。感谢

1 个答案:

答案 0 :(得分:2)

您需要有一个扩展JFrame

的新类
public class MyClass{
    //...
}

public class MyFrame extends JFrame{
    private MyClass obj;

    public MyFrame(MyClass obj){
        this.obj = obj;
        //...
    }

    //...

    public void paintComponent(Graphics g){
        // Paint obj in here
    }

}

然后,您可以这样使用:

MyClass obj = new MyClass();
MyFrame frame = new MyFrame(obj);
//...
frame.setVisible(true);