0

所以我用与该对象关联的二维数据矩阵实例化了一个对象。我对这个数据矩阵执行了所有逻辑,现在我准备好看到这个二维矩阵的视觉效果了。

我想根据矩阵中的值打印空矩形的实心矩形。

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

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

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

4

1 回答 1

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);
于 2013-08-28T08:09:36.047 回答