gpt4 book ai didi

java - 如何传递paintComponent和对象以及绘制某些东西所需的逻辑?

转载 作者:行者123 更新时间:2023-12-02 06:47:21 25 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

您需要一个扩展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);

关于java - 如何传递paintComponent和对象以及绘制某些东西所需的逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18482369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com